When looking at seasonal data I like to use charts that show a few years 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 in Plotly using the Python API?
I can only post one image in this post, but I have included the code for my Plotly attempt below. Suffice it to say that it’s pretty weak. Ideally I want to be able to give Plotly five years of data and an array with five colors and have it map each year to a color without me having to manually specify things. Basically I just don’t understand Plotly’s color-mapping paradigm well enough yet.
Code for Python example:
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
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")