【问题标题】:Create a circular barplot in python在python中创建一个圆形条形图
【发布时间】:2018-09-18 15:55:23
【问题描述】:

我有兴趣在我的项目中使用圆形条形图可视化,但不知道如何在 Python 中生成它。请参阅下面的“圆形条形图”示例。数据将以熊猫系列的形式出现 - 下面的虚拟示例模糊地反映了情节:

A 33
B 62
C 56
D 70

有什么想法吗?

【问题讨论】:

  • 您如何提供数据?一本字典?一个列表?请添加示例输入。
  • 好点,更新问题

标签: python matplotlib bar-chart


【解决方案1】:

你也可以利用被解雇的甜甜圈图:

import matplotlib.pyplot as plt
from matplotlib import cm
from math import log10

labels = list("ABCDEFG")
data = [21, 57, 88, 14, 76, 91, 26]
#number of data points
n = len(data)
#find max value for full ring
k = 10 ** int(log10(max(data)))
m = k * (1 + max(data) // k)

#radius of donut chart
r = 1.5
#calculate width of each ring
w = r / n 

#create colors along a chosen colormap
colors = [cm.terrain(i / n) for i in range(n)]

#create figure, axis
fig, ax = plt.subplots()
ax.axis("equal")

#create rings of donut chart
for i in range(n):
    #hide labels in segments with textprops: alpha = 0 - transparent, alpha = 1 - visible
    innerring, _ = ax.pie([m - data[i], data[i]], radius = r - i * w, startangle = 90, labels = ["", labels[i]], labeldistance = 1 - 1 / (1.5 * (n - i)), textprops = {"alpha": 0}, colors = ["white", colors[i]])
    plt.setp(innerring, width = w, edgecolor = "white")

plt.legend()
plt.show()

输出:

【讨论】:

  • 喜欢这个情节。感谢您抽出宝贵时间分享。
【解决方案2】:

这只是极坐标投影中的水平条形图。 Matplotlib 默认设置会让它看起来有点不同。

ax = plt.subplot(projection='polar')
ax.barh(0, math.radians(150))
ax.barh(1, math.radians(300))
ax.barh(2, math.radians(270))
ax.barh(3, math.radians(320))

但可以调整:

  • 使用set_theta_zero_location() 使条形图从北开始。
  • 使用set_theta_direction() 使条形顺时针方向移动。
  • 使用set_rlabel_position() 移动径向标签。
  • 使用set_thetagrids()set_rgrids() 设置刻度和标签。

结果非常相似:

ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)
ax.set_thetagrids([0, 96, 192, 288], labels=[0, 20, 40, 60])
ax.set_rgrids([0, 1, 2, 3], labels=['a', 'b', 'c', 'd'])

一定有办法将径向标签移动到条形的左侧,但我找不到。

PS更简洁,也许更快的方式:

ax.barh([0, 1, 2, 3], np.radians([150, 300, 270, 320]),
        color=plt.rcParams['axes.prop_cycle'].by_key()['color'])

【讨论】:

    【解决方案3】:

    这可以通过 matplotlib 完成。诀窍是在极坐标中绘制条形图。看看这个例子,取自 matplotlib 文档: https://matplotlib.org/1.2.1/examples/pylab_examples/polar_bar.html

    可以根据这些示例制作其他类型的“圆形条形图”: https://python-graph-gallery.com/donut-plot/

    更多信息https://datavizcatalogue.com/methods/donut_chart.html

    但是,我不知道使用 matplotlib 获得所需内容的直接方法。

    【讨论】:

    • 谢谢,是的,我知道那个例子并且过去使用过那个模板。但是,在该示例中,条形图沿径向“移动”,而我希望它们沿极轴方向“增长”
    • 感谢您的编辑。不幸的是,matplotlib 中的圆环图也不起作用,因为它基本上是一个中间有一个白洞的饼图。
    • 诀窍可能是通过连续减小pyplot.pieradius 参数来创建连续的饼图。这不是很方便,我同意 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多