谁能告诉我如何用python绘制像附图这样的图形?

我试着绘制了如下图所示。

df.sort_values(['Very interested'], ascending=False, axis=0, inplace=True)
ax = df.plot(kind='bar', figsize=(20, 8), width=0.8, color=['#5cb85c', 
'#5bc0de', '#d9534f'], fontsize=14)
ax.set_title("Percentage of Respondents' Interest in Data Science Areas", size=16) 
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.set_major_locator(plt.NullLocator())

for p in ax.patches:
    height = p.get_height()
    x, y = p.get_xy()
    ax.annotate('{:.2%}'.format(height/2233), (x, y + height + 0.01), size=14)
ax.legend(fontsize=14)

plt.show()

我得到了这个图

但我希望剧情是这样的。我希望剧情是这样的

解决方案:

您正在尝试的是叠加条形图。下面是一个带百分比的叠加条形图的例子。

  In [37]: import numpy as np
    ...: import matplotlib.pyplot as plt
    ...: #Get values from the group and categories
    ...: quarter = ["Q1", "Q2", "Q3", "Q4"]
    ...: mercedes = [75, 65, 16, 45]
    ...: audi = [15, 10, 27, 25]
    ...: lexus = [10, 25, 57, 30]
    ...:
    ...: #add colors
    ...: colors = ['#C70039', '#00BFFF','#FFC300','#DAF7A6','#FFDEAD']
    ...: # The position of the bars on the x-axis
    ...: r = range(len(quarter))
    ...: barWidth = 1
    ...: #plot bars
    ...: plt.figure(figsize=(10,7))
    ...: ax1 = plt.bar(r, mercedes, color=colors[0], edgecolor='white', width=barWidth, label="mercedes")
    ...: ax2 = plt.bar(r, audi, bottom=np.array(mercedes), color=colors[1], edgecolor='white', width=barWidth, label='audi')
    ...: ax3 = plt.bar(r, lexus, bottom=np.array(mercedes)+np.array(audi), color=colors[2], edgecolor='white', width=barWidth, label='lexus')
    ...: plt.legend()
    ...: # Custom X axis
    ...: plt.xticks(r, quarter, fontweight='bold')
    ...: plt.ylabel("sales")
    ...: for r1, r2, r3 in zip(ax1, ax2, ax3):
    ...:     h1 = r1.get_height()
    ...:     h2 = r2.get_height()
    ...:     h3 = r3.get_height()
    ...:     plt.text(r1.get_x() + r1.get_width() / 2., h1 / 2., "%.0f%%" % h1, ha="center", va="center", color="white", fontsize=16, fontweight="bold")
    ...:     plt.text(r2.get_x() + r2.get_width() / 2., h1 + h2 / 2., "%.0f%%" % h2, ha="center", va="center", color="white", fontsize=16, fontweight="bold")
    ...:     plt.text(r3.get_x() + r3.get_width() / 2., h1 + h2 + h3 / 2., "%0.f%%" % h3, ha="center", va="center", color="white", fontsize=16, fontweight="bold")
    ...: plt.savefig("stacked2.png")
    ...: plt.show()
Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created.

更新: 根据评论,如果你需要一个等高的堆叠条形图,将条目转换为百分比,那么所有的条形图将是等高的。

enter image description here

给TA打赏
共{{data.count}}人
人已打赏
未分类

编辑存储在 Azure Application Insights 中的痕迹表数据

2022-9-10 11:33:20

未分类

当前几个JSON项有非十进制值时,动态JSON到DataTable的反序列化会丢失小数。

2022-9-10 11:33:22

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索