【问题标题】:Creating bar chart showing percent change off the top of a bar创建条形图,显示条形顶部的百分比变化
【发布时间】:2019-04-15 15:54:27
【问题描述】:

我正在尝试创建一个关于大学授予的学位的条形图,其中显示两件事:第一个条应显示过去一年授予学位的总百分比,然后条 2、3 和 4 应显示百分比5 / 10 / 15 年前授予的学位之间的差异。

我能够将这些都表示为从 0 开始。但是有没有办法将百分比差异与 y = 当前总百分比(条 1)的顶部而不是 y = 0 对齐?

我现在创建的图表是这样的(使用基本的 pandas df.plot(kind = 'bar'):

我想要做的是移动黄色、绿色和红色条(显示 05、10、15 年增量的变化),使它们开始与蓝色条的顶部对齐(在最左边每个组)。

我已阅读以下主题:

How do I create a bar chart that starts and ends in a certain range

100% Stacked Bar Chart in MatPlotLib

Waterfall plot python?

但不确定如何制作我想要创建的精确图表。

非常感谢。

【问题讨论】:

  • 您是否有指向您心目中的图表的链接?我无法想象你想要做什么
  • 我已经通过为我想要绘制的每组 4 个数组创建数组来手动创建它:link(我无法将用于创建它的代码添加到易于阅读的方式-简而言之,我为每组 4 个数组创建了数组,并计算了每个条形的起始 y 值,然后使用 ax.bar(x_alignment, bottom = y_start, height = bar_height) 的格式将条形图从起始 y 值中绘制出来。可能是这样最好的方法并遍历我想要绘制的每个分组(并且通过 pandas 没有一个好的方法)。
  • 好的,我添加了一个我认为接近你想要实现的答案

标签: python pandas matplotlib


【解决方案1】:

使用一个基本的 2 大学示例,我通过在这些录取的绝对值之上叠加逐年录取的差异来完成您想要的操作。如果您要为多所大学执行此操作,显然您希望循环执行此操作,因此您不必显式创建每个条形图。该解决方案应该为您提供创建所需工具所需的工具。不过,我要补充一点,作为一种传达信息的方式,我认为这张图没有多大帮助。就我个人而言,我只会展示年复一年的录取情况,让眼睛弄清楚它们有多么不同,或者在上面贴上标签,标出年复一年的差异。

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({'college1' : [0.14, 0.1, 0.12, 0.07],
                        'college2' : [0.14, 0.16, 0.18, 0.12]}).T
df.columns = ['today', '5years', '10years', '15years']
width = 0.5

#plot the today bars
p1 = plt.bar([1, 4], df['today'], width, color =['#0247fe', '#175d1e'])

#plot the difference bars
p2 = plt.bar([1.5, 4.5], df['today']- df['5years'], width,
             bottom=df['5years'], color=['#6363ff', '#427741'])
p3 = plt.bar([2, 5], df['today']- df['10years'], width,
             bottom = df['10years'], color = ["#8d81ff", "#679164"])
p4 = plt.bar([2.5, 5.5], df['today']- df['15years'], width,
             bottom = df['15years'], color=["#ae9fff", "#8cac88"])

#other controls
plt.xticks([1.25, 1.75, 2.25, 2.75, 4.25, 4.75, 5.25, 5.75], ['c1 today', '5yearDiff', '10yearDiff', '15yearDiff','c2 today', '5yearDiff', '10yearDiff', '15yearDiff'],
                                                                                        rotation='vertical')
plt.ylabel("Admissions")
plt.ylim(0, 0.2)
plt.xlim(0.75, 6)
plt.gcf().set_size_inches(8, 8)
plt.subplots_adjust(bottom=0.2)
plt.show()

【讨论】:

    【解决方案2】:

    我会考虑只在 Matplotlib 中做。

    见:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html

    您将不得不编写更多代码,但您将拥有很大的灵活性。要使增长/变化条从第一个条结束处开始,您可以使用 bottom 参数。

    您可以在此处的其中一个示例中看到它的使用情况: https://matplotlib.org/gallery/lines_bars_and_markers/bar_stacked.html#sphx-glr-gallery-lines-bars-and-markers-bar-stacked-py

    【讨论】:

      猜你喜欢
      • 2018-02-20
      • 2014-09-21
      • 2021-09-22
      • 2020-12-04
      • 2020-02-29
      • 1970-01-01
      • 2018-01-22
      • 2017-03-18
      • 2023-04-02
      相关资源
      最近更新 更多