plotly - 如何制作将年份映射到线条颜色并在 x 轴上映射月份的 Plotly 图表

标签 plotly

在查看季节性数据时,我喜欢使用一次性显示几年数据的图表,其中 x 轴为 1 月到 12 月,y 轴为数值,使用颜色来区分年。下面的图表是使用 ggplot2R 中创建的。我如何使用 Python API 在 Plotly 中复制它或生成非常相似的东西?

ggplot2 chart

到目前为止,我所做的“最好的”是这样的:

Plotly

...这显然不能完成任务。理想情况下,我希望能够为 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')

enter image description here

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

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

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

关于plotly - 如何制作将年份映射到线条颜色并在 x 轴上映射月份的 Plotly 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071063/

相关文章:

python - Plotly:如何使用下拉菜单按年、月和日对数据进行子集化?

python - Plotly python:完全免费?

plotly - 如何在绘图破折号中的日期范围选择器之前获取文本标签?

python - 绘图悬停以在饼图中显示多个值

python - 聚类热图(带树状图)/Python

python - 绘制随绘图动态变化的多个轴

python - Plotly:如何为离散分类变量设置等值线图颜色?

r - 使用 htmlwidget 将交互式绘图保存到路径

plotly - Plotly Dash 布局和组件之间的概念区别是什么?

javascript - 将 angularJS 连接到 plotly