条形图-数据分析(5)

Fredreck 2020-07-04

# -*- 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();

条形图-数据分析(5)

 结果:

条形图-数据分析(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:\\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();

结果:

条形图-数据分析(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‘);

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

相关推荐