如何制作将年份映射到线条颜色并在x轴上映射月份的Plotly图表 [英] How to make Plotly chart with year mapped to line color and months on x-axis

查看:111
本文介绍了如何制作将年份映射到线条颜色并在x轴上映射月份的Plotly图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看季节性数据时,我喜欢使用一次显示几年数据的图表,其中从1月到12月的月份在x轴上运行,在y轴上的值运行,使用颜色区分年.下面的图表是使用ggplot2R中创建的.如何使用Python API在Plotly中复制它或产生非常相似的内容?

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:

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

...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.

Python示例代码:

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

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

推荐答案

我最近了解了将所有不同的迹线绘制到数据框中的列的模式:

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

上面的代码便于快速绘制,但是如果要更改默认的布局设置,可以使用下面更详细的版本来进行.查看 https://plot.ly/python/line-and -scatter/#Style-Scatter-Plots 了解更多示例.

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

或者,您可以使用cufflinks库,该库为熊猫数据帧提供了一个简单的绘图钩子:

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神奇地为熊猫数据帧(和其他对象)提供了.iplot()方法.查看 https://plot.ly/ipython-notebooks/cufflinks/ https://plot.ly/pandas/

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

这篇关于如何制作将年份映射到线条颜色并在x轴上映射月份的Plotly图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆