Answer a question

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?

Answers

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!

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐