问题
I have a dataframe in python that looks a bit like this:
Device Date Reading
Device1 1/02/17 100.33
Device1 2/02/17 300.23
Device1 3/02/17 99.00
Device2 1/02/17 11.24
Device2 2/02/17 654.00
Device2 3/02/17 4543.4
Device3 1/02/17 3243.5
Device3 2/02/17 545.43
Device3 3/02/17 4545.0
It basically has devices, dates and a reading. It's much larger than the snippet I've given.
I am trying to plot, preferably using plotly because it is is interactive and allows me to zoom, etc, which is ideal for this type of dataset.
I want to plot the date on the X axis, reading on the Y axis, and have individual lines (which are different coloured) for each device with a legend. However, everything is in one data frame and I don't want to manually add traces, which would take ages because of the size of my dataset.
I have searched high and low for a solution and nothing seems to work. I have tried the plotly site, cufflinks, but it seems quite complex and there's little info online (for cufflinks). In R, I would do something like colour=device
to signify that I want different it to be sorted by device, but I can't seem to work it out in Python.
Could anybody advise (remember everything is in one data frame)?
回答1:
I found out that using pd.groupby
method is a pretty convenient way to generate traces in loops.
import pandas as pd
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode
init_notebook_mode()
# Copy OP's example and load from clipboard
df = pd.read_clipboard()
grouped = df.groupby('Device')
data = [go.Trace(dict(x=values['Date'], y=values['Reading'], name=key,
mode='line')) for key, values in grouped]
iplot(data)
You may also set the color you want by defining beforehand a dict of device: color, for example.
来源:https://stackoverflow.com/questions/43941933/plotting-different-groups-with-plotly