Skip to content
Advertisement

How to make bar plot with varying widths and multiple values for each variable name in Python?

My question stems from the solution provided here.

In my code below, I would like to automatically take the list of variable names, x, and assign one colour for each variable from a colour map (e.g. using get_cmap). I would also only like each variable to appear once in the legend. In this example, the variables B & H have been duplicated, where I have assigned limegreen and black to them respectively.

JavaScript

Advertisement

Answer

Here, I am using dict and zip to get a single value of ‘x’, there are easier ways by importing additional libraries like numpy or pandas. What we are doing is custom building the matplotlib legend based on this article:

JavaScript

Output:

enter image description here

Details:

  1. Lineup x with a.patches using zip
  2. Assign each x as a key in dictionary with a patch, but dictionary keys are unique, so the patch for a x will be saved into the dictionary.
  3. Unpack the list of tuples for the items in the dictionary
  4. Use these as imports into plt.legend

Or you can use:

JavaScript

Using a color map:

JavaScript

Output:

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement