How to make Plotly chart with year mapped to line color and months on x-axis

旧城冷巷雨未停 提交于 2019-12-23 23:12:46

问题


When looking at seasonal data I like to use charts that show a few years of data at once, with the months running from January to December on the x-axis and the values in the y-axis, using color to distinguish the years. This chart below was created in R using ggplot2. How can I replicate it or produce something very similar in Plotly using the Python API?

So far the "best" I have done is this:

...which clearly doesn't do the job. Ideally I want to be able to give Plotly five years of data (essentially the years provide the category) with an array of two or three or five colors and have it automatically map each year to a color without me having to manually specify the individual colors itself. Basically I just don't understand Plotly's color-mapping mechanism well enough to get there.

Code for Python example:

import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np

py.sign_in('xxx','xxx')

np.random.seed(123456)
num_periods=24
monthindex=pd.date_range('1/1/2014', periods=num_periods, freq='MS')
dd = pd.DataFrame(data={'date':monthindex,
                        'c1': np.random.uniform(10, 20, size=num_periods),
                        'c2': np.random.uniform(30, 40, size=num_periods)},
                  index=monthindex,
)
dd['year'] = dd['date'].dt.year
dd['monthname'] = dd['date'].dt.strftime('%b')

outdata = [
    go.Scatter(
        x=dd['monthname'], # assign x as the dataframe column 'x'
        y=dd['c1'],
    )
]

layout = go.Layout(
    showlegend=True,
    title="'Stacking' years in plotly",
    xaxis=dict(
        type='category'
    )
)

Code for R example:

library(ggplot2)

dd <- data.frame(date = seq(as.Date("2014/1/1"),
                     by = "month",
                     length.out = 24),
                 c1 = runif(24, min = 10, max = 20))

dd$month <- as.integer(strftime(dd$date, "%m"))
dd$year <- strftime(dd$date, "%Y")

xscale <- data.frame(breaks = c(1,2,3,4,5,6,7,8,9,10,11,12),
                     labels = c('Jan','Feb','Mar','Apr',
                         'May','Jun','Jul','Aug','Sep',
                         'Oct','Nov','Dec'))


ggplot(dd, aes(month, c1)) +
    geom_line(aes(colour = factor(year))) +
        scale_x_continuous(breaks = xscale$breaks,
                           labels = xscale$labels) +
            scale_colour_manual("year",values=c("Red","Blue")) +
                ggtitle("'Stacking' years in ggplot2")

回答1:


I just recently learned the pattern of making all the different traces I want to plot into columns in a dataframe:

dd = dd.pivot_table('c1', 'monthname', 'year')
py.iplot([{
    'x': dd.index,
    'y': dd[col],
    'name': col
}  for col in dd.columns])

The above code is convenient for plotting quickly, but if you want to change the default layout settings, you can do so with the more verbose version below. Check out https://plot.ly/python/line-and-scatter/#Style-Scatter-Plots for more examples.

import plotly.plotly as py
import plotly.graph_objs as go

my_data = [{
    'x': dd.index,
    'y': dd[col],
    'name': col
}  for col in dd.columns]

my_layout = {'title':'my graphtitle',
          'xaxis':{'title':'x axis title'},
          'yaxis':{'title':'y axis title')
         }
fig = go.Figure(data=my_data, layout=my_layout)
py.iplot(fig, filename='scatter_plot')

Alternatively, you could use the cufflinks library which provides a simple plotting hook for pandas dataframes:

import cufflinks
dd = dd.pivot_table('c1', 'monthname', 'year')
dd.iplot()

cufflinks magically gives pandas dataframes (and other objects) the .iplot() method. Check out https://plot.ly/ipython-notebooks/cufflinks/ and https://plot.ly/pandas/



来源:https://stackoverflow.com/questions/35071063/how-to-make-plotly-chart-with-year-mapped-to-line-color-and-months-on-x-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!