Too much space between bars in matplotlib bar char

2019-07-29 00:38发布

I am trying to create a bar chart with matplotlib.

The x-axis data is a list with years: [1950,1960,1970,1980,1990,1995-2015]

The y-axis data is a list with equal amount of numbers as in years.

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. How can I make it, so that there is no gap inbetween the bars 1950-1995. I get that it has intervals of 10 years, but it doesn't look good.

Any help would be appreaciated.

1条回答
女痞
2楼-- · 2019-07-29 00:59

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

enter image description here

查看更多
登录 后发表回答