Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar chart in matplotlib using a colormap

I have a df with two columns:

  • y: different numeric values for the y axis
  • days: the names of four different days (Monday, Tuesday, Wednesday, Thursday)

I also have a colormap with four different colors that I made myself and it's a ListedColorMap object.

I want to create a bar chart with the four categories (days of the week) in the x axis and their corresponding values in the y axis. At the same time, I want each bar to have a different color using my colormap.

This is the code I used to build my bar chart:

def my_barchart(my_df, my_cmap):
  fig = plt.figure()
  ax = fig.add_axes([0,0,1,1])
  ax.bar(my_df['days'], my_df['y'], color=my_cmap)
  return fig

However, I get the following error: "object of type 'ListedColormap' has no len()", so it seems that I'm not using my_cmap correctly.

If I remove that from the function and run it, my bar chart looks ok, except that all bars have the same color. So my question is: what is the right way to use a colormap with a bar chart?

like image 674
aprendiz Avatar asked Sep 25 '20 17:09

aprendiz


People also ask

How do you plot a value in a bar chart in Python?

Call matplotlib. pyplot. barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable.

What is Matplotlib colormap?

Scientifically, the human brain perceives various intuition based on the different colors they see. Matplotlib provides some nice colormaps you can use, such as Sequential colormaps, Diverging colormaps, Cyclic colormaps, and Qualitative colormaps.

How do you color a bar graph in Python?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.


2 Answers

The color argument wants either a string or an RGB[A] value (it can be a single colour, or a sequence of colours with one for each data point you are plotting). Colour maps are typically callable with floats in the range [0, 1].

So what you want to do is take the values you want for the colours for each bar, scale them to the range [0, 1], and then call my_cmap with those rescaled values.

So, say for example you wanted the colours to correspond to the y values (heights of the bars), then you should modify your code like this (assumes you have called import numpy as np earlier on):

def my_barchart(my_df, my_cmap):
    rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y))

    fig = plt.figure()
    ax = fig.add_axes([0,0,1,1])
    ax.bar(my_df['days'], my_df['y'], color=my_cmap(rescale(my_df['y'])))
    return fig

Here is a self-contained minimal example of using the color argument with the output from a cmap:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

my_cmap = plt.get_cmap("viridis")
rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y))

plt.bar(x, y, color=my_cmap(rescale(y)))
plt.savefig("temp")

Output:

enter image description here

like image 162
Jake Levi Avatar answered Oct 04 '22 06:10

Jake Levi


Okay, I found a way to do this without having to scale my values:

def my_barchart(my_df, my_cmap):
  fig = plt.figure()
  ax = fig.add_axes([0,0,1,1])
  ax.bar(my_df['days'], my_df['y'], color=my_cmap.colors)
  return fig

Simply adding .colors after my_cmap works!

like image 39
aprendiz Avatar answered Oct 04 '22 06:10

aprendiz