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

问题描述 投票:0回答:1

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

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()

我得到了这个图

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

python database matplotlib data-visualization
1个回答
0
投票

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

  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

© www.soinside.com 2019 - 2024. All rights reserved.