条形图-数据分析(5)
# -*- coding: utf-8 -*- import numpy; import matplotlib; from pandas import read_csv; from matplotlib import pyplot as plt; font = { ‘family‘ : ‘SimHei‘ }; matplotlib.rc(‘font‘, **font); data = read_csv(‘D:\\python\\5.4\\data.csv‘); d1 = ‘手机品牌‘; d2 = ‘通信品牌‘; v = "月消费"; gb = data.groupby(by=[d1, d2])[‘月消费(元)‘].agg({v: numpy.sum}); d1size = gb.index.levels[0].size; d2size = gb.index.levels[1].size; #建立x轴的序列 index = numpy.arange(d1size); colors=[‘r‘, ‘g‘, ‘b‘]; #遍历每一种颜色的数据 for i in range(0, d2size): print(i); subgb = gb[v][gb.index.labels[1]==i]; bar = plt.bar(index*d2size + i, subgb, color=colors[i]); #移动柱形图(-向右;+向左,往原点靠拢) lIndex = numpy.arange(d1size)*d2size; plt.xticks(lIndex + 3/2, gb.index.levels[0]); #显示图例 plt.legend(gb.index.levels[1]); plt.show();
结果:
柱形重叠:
# -*- coding: utf-8 -*- import numpy; import matplotlib; from pandas import read_csv; from matplotlib import pyplot as plt; font = { ‘family‘ : ‘SimHei‘ }; matplotlib.rc(‘font‘, **font); data = read_csv(‘D:\\PA\\5.4\\data.csv‘); d1 = ‘手机品牌‘; d2 = ‘通信品牌‘; v = "月消费"; gb = data.groupby(by=[d1, d2])[‘月消费(元)‘].agg({v: numpy.sum}); d1size = gb.index.levels[0].size; d2size = gb.index.levels[1].size; index = numpy.arange(d1size); colors = [‘r‘, ‘g‘, ‘b‘]; bsum = index*0.0; for i in range(0, d2size): print(i); subgb = gb[v][gb.index.labels[1]==i]; bar = plt.bar(index, subgb, color=colors[i], bottom=bsum); bsum += subgb; plt.xticks(index+1/2, gb.index.levels[0]); plt.legend(gb.index.levels[1]); plt.show();
结果:
直方图:
# -*- coding: utf-8 -*- import numpy; import matplotlib; from pandas import read_csv; from matplotlib import pyplot as plt; font = { ‘family‘ : ‘SimHei‘ }; matplotlib.rc(‘font‘, **font); data = read_csv(‘D:\\python\\5.4\\data.csv‘); gb = data.groupby( by=[‘手机品牌‘] )[‘月消费(元)‘].agg({ ‘月消费‘: numpy.sum }); index = numpy.arange(gb[‘月消费‘].size); #竖向柱形图 plt.bar(index, gb[‘月消费‘], 1, color=‘G‘); plt.show(); plt.bar(index, gb[‘月消费‘], 1, color=‘G‘); plt.xticks(index + 1/2, gb.index); plt.show(); #横向柱形图 plt.barh(index, gb[‘月消费‘], 1, color=‘G‘); plt.yticks(index + 1/2, gb.index); plt.show();
相关推荐
茄肥猫的窝 2020-10-29
kkbb 2020-10-27
gallon00 2020-10-16
flyfor0 2020-11-16
aiwozhiai 2020-10-06
HashData0 2020-09-18
GooTal 2020-09-16
qiujiahao 2020-09-15
Dimples 2020-09-15
qiujiahao 2020-09-11
wangquannuaa 2020-08-30
逍遥友 2020-08-21
nxcjh 2020-08-17
CodeAsWind 2020-08-17
BMUranus 2020-08-16
zlfing 2020-08-16
wordmhg 2020-08-16
Cocainebai 2020-08-15
子昊的茶会 2020-08-04