简体   繁体   English

matplotlib条形图中条形之间的空间太大

[英]Too much space between bars in matplotlib bar chart

I am trying to create a bar chart with matplotlib. 我正在尝试用matplotlib创建一个条形图。

The x-axis data is a list with years: [1950,1960,1970,1980,1990,1995-2015] x轴数据是具有年份的列表:[1950,1960,1970,1980,1990,1995-2015]

The y-axis data is a list with equal amount of numbers as in years. y轴数据是具有与年份相同数量的列表。

This is my code: 这是我的代码:

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()

And the outcome is the following: Too much space between bars 结果如下: 酒吧之间的空间太大

As you can see the gaps between 1950-1960 is huge. 正如你所看到的,1950 - 1960年间的差距是巨大的。 How can I make it, so that there is no gap inbetween the bars 1950-1995. 我怎样才能做到这一点,以便在1950-1995之间没有间隙。 I get that it has intervals of 10 years, but it doesn't look good. 我知道它有10年的间隔,但看起来不太好。

Any help would be appreaciated. 任何帮助都会被贬低。

You need to plot the population data as a function of increasing integers. 您需要将总体数据绘制为增加整数的函数。 This makes the bars have equal spacings. 这使得条具有相等的间距。 You can then adapt the labels to be the years that each graph represents. 然后,您可以将标签调整为每个图表所代表的年份。

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()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM