如何制作 Plotly 图表,其中年份映射到 x 轴上的线条颜色和月份

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

在查看季节性数据时,我喜欢使用一次显示几年数据的图表,x 轴为 1 月至 12 月 运行 个月,y 轴为值,用颜色来区分岁月。下面的图表是在 R 中使用 ggplot2 创建的。我如何使用 Python API?

在 Plotly 中复制它或生成非常相似的东西

到目前为止我做的"best"是这样的:

...这显然不符合要求。理想情况下,我希望能够为 Plotly 五年的数据(基本上是年份提供类别)提供两种或三种或五种颜色的数组,并让它每年自动映射到一种颜色,而无需我手动指定各种颜色本身。基本上我只是不太了解 Plotly 的颜色映射机制,无法到达那里。

Python 示例的代码:

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'
    )
)

R 示例代码:

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")

我最近刚刚学会了将我想要绘制的所有不同轨迹绘制到数据框中的列中的模式:

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

以上代码便于快速绘图,但如果您想更改默认布局设置,可以使用下面更详细的版本。查看 https://plot.ly/python/line-and-scatter/#Style-Scatter-Plots 以获取更多示例。

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')

或者,您可以使用 cufflinks 库,它为 pandas 数据帧提供了一个简单的绘图挂钩:

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

cufflinks 神奇地为 pandas 数据帧(和其他对象)提供了 .iplot() 方法。查看 https://plot.ly/ipython-notebooks/cufflinks/ and https://plot.ly/pandas/