在matplotlib(Python)中创建图表(未知类型-图片中的示例)

klh5stk1  于 2023-03-03  发布在  Python
关注(0)|答案(1)|浏览(124)

我看到了一个特定的图表类型,其可视化的数据,我真的很喜欢。遗憾的是,我不知道它的名称,以查找教程。Screenshot
我有一些数据,这将完全适合这种图表类型(海事组织)。但我需要一些帮助来创建这一点。我有一些基本的Python知识,并做了一些绘图之前,但没有这样的。
这是我想要可视化的数据

countries = ["Bolivien","Argentinien","US","Chile","Australien","China","Deutschland","DR" "Kongo","Kanada","Mexiko","Tschechien","Serbien","Weitere"]
resources = [21,20,12,11,7.9,6.8,3.2,3,2.9,1.7,1.3,1.2,6]
percentages = [21.43,20.41,12.24,11.22,8.06,6.94,3.27,3.06,2.96,1.73,1.33,1.22,6.12]

国家/地区应该是x轴值。条形应该是百分比的高度,y轴总计为100%,如示例图片所示。不同的条形应该以资源值作为标签。条形不需要应用配色方案。
人们会怎样创造这个呢?
任何帮助都非常感谢!谢谢

1wnzp6jl

1wnzp6jl1#

我试图这样做,因为我没有读评论,其中提到,这是一个瀑布图的时间。
我最初的想法是为每个可能的值创建一个补丁,并使用一个变量 sum_percentage 来跟踪每个矩形的起始值,这将强制手动定义x轴和y轴的限制,否则它们将不会更新。
结果:x1c 0d1x
和代码:

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np

countries = ["Bolivien","Argentinien","US","Chile","Australien","China","Deutschland","DR" "Kongo","Kanada","Mexiko","Tschechien","Serbien","Weitere"]
resources = [21,20,12,11,7.9,6.8,3.2,3,2.9,1.7,1.3,1.2,6]
percentages = [21.43,20.41,12.24,11.22,8.06,6.94,3.27,3.06,2.96,1.73,1.33,1.22,6.12]

square_width = 1 # Sets width in x axis 
center_x = np.arange(0.5,12.6,1) # center of each bar, employed for the x-ticks

# Facecolors
colors = plt.cm.spring(np.linspace(0,1,len(countries)))

sum_percent = 0 # Tracks current added value of percentages
fig, ax = plt.subplots(1, 1)
for ii in range(len(countries)): # For each country
    # Create and add corresponding patch
    left, bottom, width, height = (center_x[ii]-square_width/2, 
                                   sum_percent, 
                                   square_width, 
                                   percentages[ii])
    rect = plt.Rectangle((left, bottom), width, height,
                     facecolor=colors[ii], alpha=0.5)
    ax.add_patch(rect)
    # Create and add text in center of patches
    ax.text(center_x[ii], sum_percent + percentages[ii]/2,str(resources[ii]), va = 'center', ha = 'center')
    # Update sum_percent
    sum_percent = sum_percent + percentages[ii]  
plt.xticks(center_x, countries, rotation = 45)
plt.ylabel('Percentage (%)')
plt.ylim([0 ,100]) # Because patches does not change the y limits
plt.xlim([0, len(countries)])
plt.tight_layout()
plt.show()

编辑:如果您希望在更改国家/地区列表时更新所有内容,请执行以下操作:

center_x = np.arange(0.5,12.6,1) # center of each bar, employed for the x-ticks

应该更新为这样的内容:

center_x = np.arange(square_width/2, len(countries)-square_width/2+0.1, square_width) # center of each bar, employed for the x-ticks

相关问题