matplotlib 在For循环中向条形图添加百分比变化值[重复]

wsewodh2  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(116)

此问题已在此处有答案

How to plot in multiple subplots(13个回答)
Plotting dataframe columns using a for loop [closed](2个答案)
Add a percent sign to a dataframe column(3个答案)
Change format of bar_label to percent [duplicate](3个答案)
bar labels with new f-string format style(1个回答)
上个月关门了。
我使用for循环创建了一系列单独的条形图(不是子图机制),但现在想添加按年变化的百分比作为条形图标签。我在Python中创建了两个单独的df来保存水平值和百分比变化值。我能够输出正确的条形图,并将正确的百分比变化作为条形图标签,但是它也开始输出太多的条形图。比我在我的df中的多得多。这很可能是由于嵌套的for循环,但是我还没有找到一种方法来解决这个问题。
我的相框也是这样设置的(索引为2013-2027年,每列为年度数据类别)。我还确定了一个特殊的时间框架用于创建条形图。ak df是一个水平,akp是一个百分比变化。我想使用ak中的水平数据创建单独的条形图,然后将akp中发现的百分比变化添加到条形标签中。下面的代码给了我我正在寻找的~一般~,但也创建了许多图形的方式。我如何才能让它在ak df中每列生成1个图形,同时只将akp df用于条形标签?

  1. ak = ak.set_index("combo")
  2. ak = ak.T
  3. akp = ak.pct_change()
  4. colors = ['blue', 'blue','blue', 'blue', 'blue', 'red', 'red', 'red' ]
  5. timeframe = ak["2019":"2026"]
  6. timeframe1 = akp["2019":"2026"]
  7. for i in timeframe.columns:
  8. for i in timeframe1.columns:
  9. plt.figure()
  10. barplot = plt.bar(timeframe.index, timeframe[i], color = colors)
  11. plt.grid(False)
  12. plt.ylabel('A')
  13. plt.bar_label(barplot, labels = round(timeframe1[i],2), label_type= "edge")
qncylg1j

qncylg1j1#

如果没有一些样本数据,这有点难以理解,但是:
1.我可以看到你在两个循环中都使用了i; 2.如果你在嵌套循环中创建图形,代码将创建的图形数量是N * N,其中N是列数。
这能解决你的问题吗?

  1. for i in timeframe.columns:
  2. plt.figure()
  3. barplot = plt.bar(timeframe.index, timeframe[i], color = colors)
  4. plt.grid(False)
  5. plt.ylabel('A')
  6. plt.bar_label(barplot, labels = round(timeframe1[i],2), label_type= "edge")
  7. # if you want percentage signs try using an iterator:
  8. plt.bar_label(barplot, labels = [str(v) + '%' for v in round(timeframe1[i],2)], label_type= "edge")

相关问题