Too much space between bars in matplotlib bar chart

自闭症网瘾萝莉.ら 提交于 2019-12-24 10:14:10

问题


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:


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



来源:https://stackoverflow.com/questions/43094727/too-much-space-between-bars-in-matplotlib-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!