Plot Time Series With Colorbar In Pandas + Matplotlib
I'm trying to plot a colorbar below this chart, where the color depends on when each of the time series starts: The code generated to create the plot is this: import pandas as pd
Solution 1:
The first point is that you need to create a ScalarMappable for your colorbar. You need to define the colormap, which in your case is 'viridis'
and specify the maximum and minimum of the values you want for the colorbar. Then because it uses numeric time values you want to reformat those.
import matplotlib.pyplot as plt
import pandas as pd
# Define your mappable for colorbar creation
sm = plt.cm.ScalarMappable(cmap='viridis',
norm=plt.Normalize(vmin=df.index.min().value,
vmax=df.index.max().value))
sm._A = []
df.plot(legend=False, colormap='viridis', figsize=(12,7));
cbar = plt.colorbar(sm);
# Change the numeric ticks into ones that match the x-axis
cbar.ax.set_yticklabels(pd.to_datetime(cbar.get_ticks()).strftime(date_format='%b %Y'))
Post a Comment for "Plot Time Series With Colorbar In Pandas + Matplotlib"