Matplotlib 柱状图间距过大问题

2024-09-29 01:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用matplotlib创建一个条形图。在

x轴数据为带年份的列表:[19501960197019801995-2015]

y轴数据是一个数字量与年份相等的列表。在

这是我的代码:

import csv
import matplotlib.pyplot as plt

path = "bevoelkerung_entwicklung.csv"



with open(path, 'r') as datei:
    reader = csv.reader(datei, delimiter=';')
    jahr = next(reader)
    population = next(reader)

population_list = []

for p in population:
    population_list.append(str(p).replace("'",""))

population_list = list(map(int, population_list))
jahr = list(map(int, jahr))

datei.close()

plt.bar(jahr,population_list, color='c')

plt.xlabel('Year')
plt.ylabel('Population in 1000')
plt.title('Population growth')
plt.legend()
plt.show()

结果如下: Too much space between bars

如你所见,1950-1960年之间的差距是巨大的。我怎样才能做到这一点,这样1950年到1995年这两道杠之间就没有空隙了。我知道它有10年的间隔期,但看起来不太好。在

任何帮助都会得到回报的。在


Tags: csv数据pathimport列表matplotlibasplt
1条回答
网友
1楼 · 发布于 2024-09-29 01:25:28

您需要将人口数据绘制为整数递增的函数。这使得这些杆的间距相等。然后,您可以将标签调整为每个图表所代表的年份。在

import matplotlib.pyplot as plt
import numpy as np

jahre = np.append(np.arange(1950,2000,10), np.arange(1995,2017))
bevoelkerung = np.cumsum(np.ones_like(jahre))
x = np.arange(len(jahre))

plt.bar(x, bevoelkerung)
plt.xticks(x, jahre, rotation=90)
plt.show()

enter image description here

相关问题 更多 >