本帖最后由 BIO-张磊 于 2020-6-25 21:50 编辑
把这段代码保存为一个新的文件,和你那个table.csv放在同一个文件夹下,双击运行代码文件,就会出来你要的图。pandas numpy 和matplotlib这三个没有,就自己安装,满意请采纳
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def read_data(url,col_a = 0,col_b = 1):
#读取数据
global data,new_data
data = pd.read_csv(url)
data_col = data.columns.to_list()
data = data[[data_col[col_a],data_col[col_b]]]
#确定index
data_index = sorted(list(data.iloc[:,0].drop_duplicates()))
#data_columns = sorted(list(data.iloc[:,1].drop_duplicates()))
new_data = pd.DataFrame()
#统计columns的次数
for i in data_index:
data_i = pd.DataFrame((data[data.iloc[:,0] == i].iloc[:,1]).value_counts()).T
data_i.index = [i]
new_data = pd.concat([new_data,data_i])
else:
if np.any(new_data.isnull()):#如果有缺失值
new_data.fillna(value = 0,inplace = True)
#设置stacked和T两个变量,可以让bar绘制四种类型的图
def bar(data_bar,width = 0.5,edgecolor = "white",stacked = False,T = False):
#兼容中文
plt.rcParams['font.sans-serif'] = ['SIMHEI']
if T:#若T为True,转置index和columns
data_bar = data_bar.T
if stacked :#stacked为True绘制堆积柱状图
data_bar.plot.bar(width = width,stacked = stacked)
else:
data_bar.plot.bar(width = width,edgecolor = edgecolor)
plt.show()
if __name__ == "__main__":
read_data("table.csv",2,6)
bar(new_data,stacked = False,T = False)
bar(new_data,stacked = False,T = True)
bar(new_data,stacked = True,T = False)
bar(new_data,stacked = True,T = True)
|