【问题标题】:overlapping python stacked bar graphs重叠的python堆积条形图
【发布时间】:2019-04-15 14:10:25
【问题描述】:

有没有办法在每个 x 位置不同的多个条形图中设置每个数据集的 zorder,以便所有信息都可见。

axes.bar(position,data_1,color='g')
axes.bar(position,data_2,color='r')
axes.bar(position,data_3,color='b')

例如,如果蓝色值大于绿色值,则绿色将隐藏在后面,反之亦然。将 alpha 值设置为低于 1 的值会通过混合颜色创建 3 种以上的颜色。

【问题讨论】:

  • 您可能需要手动检查哪个栏更高,并为其中一个类使用不同的 zorder 运行 bar() 两次。
  • 是的。随着要绘制的数据集越来越多,这将变得更加复杂。
  • 不一定。如果您遍历这些垃圾箱并一一排序,那应该不会太难。不过,通常这种情节是通过将条形相邻放置来完成的。

标签: python matplotlib bar-chart overlap z-order


【解决方案1】:

你很幸运! plot 有一个zorder kwarg。

为了确定,我在bar 上测试了它,并使用了我放置的示例。

summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
                label="Summer", zorder=2)

winter = ax.bar(index, df["Crime Type Winter"].value_counts(),
                bar_width, label="Winter", zorder=1)

给予:

如果我反转它:

summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
                label="Summer", zorder=1)

winter = ax.bar(index, df["Crime Type Winter"].value_counts(),
                bar_width, label="Winter", zorder=2)

编辑:我查看了其中的“条中的条”部分,并且如其他地方的 cmets 所述,您似乎需要根据其值的排序手动设置 zorder。您可能希望根据计算得到的 zorder 修改条形宽度以获得该视觉效果。

为了清楚起见,下面给出了我用作参考示例的完整代码:

import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

s = "Crime Type Summer|Crime Type Winter".split("|")
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]) for j in range(300)] for x in s}
df = pd.DataFrame(j)

index = np.arange(5)
bar_width = 0.35

fig, ax = plt.subplots()
summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
                label="Summer", zorder=1)

winter = ax.bar(index, df["Crime Type Winter"].value_counts(),
                bar_width, label="Winter", zorder=2)

ax.set_xlabel('Category')
ax.set_ylabel('Incidence')
ax.set_title('Crime incidence by season, type')
ax.set_xticks(index)
ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
ax.legend()

plt.show()

【讨论】:

  • 对不起,我的意思是说隐藏行为是不受欢迎的。无论哪个更大,我都希望能够同时看到这两个数据集。
  • 那么基本上是酒吧内的酒吧?而不是并排放置酒吧
  • 我想你明白我想要完成什么。是的
  • 已对此进行了编辑,但我认为您不会喜欢它...您是否有理由不能使用并排条形图案?实现起来似乎要简单得多
  • 当有很多 x 位置时,并排变得难以阅读
【解决方案2】:

一种方法是在每个条形位置分别对条形进行排序:

import matplotlib.pyplot as plt
import numpy as np

L = 5

heights_a = 10. + np.random.randn(L)
heights_b = 10. + np.random.randn(L)
heights_c = 10. + np.random.randn(L)

position = np.arange(L)
colors = ['C0', 'C1', 'C2']

plt.figure()

for x, ha, hb, hc in zip(position, heights_a, heights_b, heights_c):
    for i, (h, c) in enumerate(sorted(zip([ha, hb, hc], colors))):
        plt.bar(x, h, color=c, zorder=-i)

plt.show()

看起来像这样:

【讨论】:

  • 哦,这很甜蜜。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-03-11
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 2015-07-28
  • 1970-01-01
相关资源
最近更新 更多