又是educoder上的一个题目
数据文件长这样:
编程要求
(文件结构就是一个main.py调用了student.py,数据文件在同级目录下)请仔细阅读右侧代码,结合相关知识,在 Begin-End 区域内进行代码补充,使用数值规约的无参方法中的直方图展示不同年龄的发病次数。
图片生产要求如下:
设置图片大小 figsize=(10,10);
图形保存到 Task1/img/T1.png。
预期输出:
尝试作答:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def student():
train = pd.read_csv('Task1/diabetes_null.csv', na_values=['#NAME?'])
#********* Begin *********#
x=train['Age'].value_counts()
plt.hist(x,color=None,bins=60)
plt.figsize=(10,10)
plt.savefig('Task1/img/T1.png')
plt.show()
#********* End *********#
遇到的问题
同类型显示为同一个颜色,color参数也只能调整为另一个相同颜色
x轴不一样的原因可能有两个,分箱个数和精度。有些数值会直接显示为0
实在解决不了了,上答案:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def student():
train = pd.read_csv('Task1/diabetes_null.csv', na_values=['#NAME?'])
train['Insulin'] = train['Insulin'].fillna(100)
train['SkinThickness'] = train['SkinThickness'].fillna(train['SkinThickness'].median())
train['BloodPressure'] = train['BloodPressure'].fillna(train['BloodPressure'].median())
train['BMI'] = train['BMI'].fillna(train['BMI'].mean())
train['Glucose'] = train['Glucose'].fillna(train['Glucose'].mean())
#********* Begin *********#
plt.figure(figsize=(10,10))
x=pd.Series(train['Age'])
count=x.value_counts()
count.plot(kind='bar')//这里不是使用plt.hist
plt.savefig("Task1/img/T1.png")
plt.show()
#********* End *********#
原来是不熟悉pandas
在Python中,任何不可变的对象(例如整数,布尔值,字符串,元组)都是可哈希的,这意味着其值在其生存期内不会改变。 这使Python可以创建一个唯一的哈希值来标识它,字典可以使用它来跟踪唯一的键,并使用集合来跟踪唯一的值。 这就是为什么Python要求我们对字典中的键使用不可变的数据类型。
Return a Series containing counts of unique values.返回的也是一个序列
如何做出好看的严谨的直方图
原图:
plt.figure() #初始化一张图
x = life_cycle
plt.hist(x) #直方图关键操作
plt.grid(alpha=0.5,linestyle='-.') #网格线,更好看
plt.xlabel('Life Cycle /Month')
plt.ylabel('Number of Events')
plt.title(r'Life cycle frequency distribution histogram of events in New York')
plt.show()
原码:
问题:
不能准确表达信息、凸显信息,
横坐标有多余的部分,
分箱bins也不够细致,
还可以加上拟合线
plt.figure() #初始化一张图
x = life_cycle
width = 40
n, bins, patches = plt.hist(x,bins = width,range=(0,width),color='blue',alpha=0.5)
#print(n)
#print(bins)
#print(patches)
#hist是有返回值的
#n对应着纵坐标的值,bins对应横坐标的值,patches是具体的条形对象。
plt.grid(alpha=0.5,linestyle='-.') #网格线,更好看
plt.xlabel('Life Cycle /Month')
plt.ylabel('Number of Events')
plt.title(r'Life cycle frequency distribution histogram of events in New York') #+citys[i])
plt.xticks(np.arange(0,width,2))# 刻度的精度值
plt.plot(bins[0:width]+((bins[1]-bins[0])/2.0),n,color='red')#利用返回值来绘制区间中点连线
plt.show()