Search code examples
pythonpandasplotcolorbar

Matplotlib Plot and Colorbar issues


I have the below plot, however, I am struggling with the 3 questions below....

  1. How can I move X-axis labels (1-31) to the top of the plot?
  2. How can I change formating of the color bar from (7000 to 7k etc.)
  3. How can I change the color from gray to another cmap like "Reds"?
  4. Can I change the figure size? plt.figure(figsize=(20,10)) does not work?

enter image description here

data1 = pd.read_csv("a2data/data1.csv")
data2 = pd.read_csv("a2data/data2.csv")
merged_df = pd.concat([data1, data2])
merged_df.set_index(['month', 'day'], inplace=True)
merged_df.sort_index(inplace=True)
merged_df2=merged_df.groupby(['month', 'day']).deaths.mean().unstack('day')   
plt.imshow(merged_df2)
plt.xticks(np.arange(merged_df2.shape[1]), merged_df2.columns)
plt.yticks(np.arange(merged_df2.shape[0]), merged_df2.index)
plt.colorbar(orientation="horizontal")
plt.show()

Solution

  • Let's try:

    # create a single subplot to access the axis
    fig, ax = plt.subplots()
    
    # passing the `cmap` for custom color
    plt.imshow(df, cmap='hot', origin='upper')
    
    # draw the colorbar
    cb = plt.colorbar(orientation="horizontal")
    
    # extract the ticks on colorbar
    ticklabels = cb.get_ticks()
    
    # reformat the ticks
    cb.set_ticks(ticklabels)
    cb.set_ticklabels([f'{int(x//1000)}K' for x in ticklabels])
    
    # move x ticks to the top
    ax.xaxis.tick_top()
    
    plt.show()
    

    Output:

    enter image description here