首页 > 解决方案 > matplotlib - 如何并排绘制条形图以比较两列之间的值

问题描述

我有一个由 2008 年和 2013 年分隔的某些值的数据集。但是,当我使用 matplotlib 绘制它们时,条形图中只有 2008 年的值出现。

我想将 2008 年和 2013 年的条形图并排比较。

数据图像

到目前为止,我只设法制作了这个 2008 年的值,以 flat_type 分隔

import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('C:\data/IT8701_CA2_Data/hdb-resident-population-by-flat-type.csv', 
                        skip_header=1, 
                        dtype=[('shs_year','U50'),('flat_type','U50'),('resident_population','i8')], delimiter=",",
                        missing_values=['na','-'],filling_values=[0])`
labels = list(set(data['flat_type']))
labels.sort()
residents = np.arange(0,len(labels))
residents_values = data[['flat_type','resident_population']]

values = residents_values['resident_population']

units_values = {}

for i in labels:
valuesforFY = values[residents_values['flat_type']==i] 
print("No.of Residents in Flat_type: " + i + " is {}".format(valuesforFY))
#the line below is critical
units_values[i] = valuesforFY

plt.figure(1, figsize=(8,8))
xdata =  list(units_values.keys())
ydata = [i[0] for i in units_values.values()]
barchart = plt.bar(xdata, ydata, color='b')

标签: pythonpandasmatplotlibbar-chart

解决方案


这使用了熊猫,但如果你想改变你的数据结构,应该会给你你需要的东西。

import pandas as pd

df = pd.DataFrame([['2008', '2008', '2013', '2013'],['a','b','a','b'], [3,7,5,6]]).T
df.columns = ['year', 'type', 'value']
df.set_index(['year', 'type'], inplace=True)

df.unstack().plot.bar()

在此处输入图像描述


推荐阅读