Python 数据分析可视化--Matplotlib
类 型
语 句
备 注
固定通用语句
import matplotlib.pyplot as plt
引入可视化模块
Params[‘font,sans-serif’]=[‘SimHei’]
Params[‘font.family’]=’sans-serif’
params[‘axes.unicode_minus’]=False
规定字体
fig=plt.figure()
ax1=plt.subplot(221)
ax2=plt.subplot(222)
matplotlib中subplotax3=plt.subplot(223)
ax4=plt.subplot(224)
创建画布;
画布的四个模块
id(b=None,which=’major/minor/both’,axis=’both/x/y’)
增加图形背景
参数b:设置是否显示grid,如果要显示grid,将b参数设置为True
参数which:设置坐标轴的分割标示线的类型
参数axis:指定绘制gird的坐标轴,取值为both,x或y
plt.xlabel(‘xxxxxx’)
规定X轴的标题
plt.ylabel(‘xxxxxx’)
规定Y轴的标题
plt.ylim(2.5,6.5)
Y轴的数值范围
icks(range(9),[‘1月’,’2月’,’3月’,’4月’, ‘5月’,’6月’,’7月’,’8月’,‘9月’],rotation=45)
X轴的标签,
rotataion指的是标签的角度
icks(range(10),)
Y轴的标签
plt.title(‘xxxxx’,loc=’right’)
loc显示标题的位置
plt.legend(loc=’best’,prop=getChineseFont())
增加图例;prop增加中文显示
plt.show()
显示位置
曲线图
plt.plot(data,label=’成绩’,color=’r’,marker=’o’,linestyle=”--”,linewidth=1)
案例:多条曲线图
lineslist=plt.plot(x1,y1,x2,y2,x3,y3)
plt.setp(lineslist,color=’r’)
类型
名称取值
符号取值
实线
solid
‘-’
虚线
dashed
‘--’
线点
dashdot
‘-.’
点线
dotted
‘:’
不画线
None
linestyle:线的类型;
linewidth:线的宽度;
color:线的颜
label:数据标签
marker:数据点的形状:
主要有‘o’和’v’
语 句
备 注
柱形图
plt.bar(left=[2,3,4,5],height=[228,35,81,1],bottom=2,width=1,color=’r’,
edgecolor=’b’)
水平柱状图
plt.barh([2,3,4,5],height=[228,35,81,1],height=1.0,color=’r’,edgecolor=’b’)
饼形图
plt.pie(data,labels=([‘语文’,’数学’,’英语’,’物理’]),color=([‘b’,’r’,’y’,’’,’c’]),shadow=True)
shadow:是否显示阴影
直方图
plt.hist(data,bins=12)
bins:设置直方图分布图区间的个数;
orientation:horizontal显示横向直方图;vertical显示水平直方图;
cumulative:显示为True累计直方图;
plt.hist(data,bins=12,orientation=’horizontal’)
plt.hist(Close,range=(2.3,5.5),orientation=’vertical’,cumulative=True,
color=’r’,edgecolor=’b’)
箱型图
plt.boxplot(data,labels=(‘open,’high’,’low’,’close’))
散点图
plt.scatter(data-x,data-y,marker=’o’,alpha=0.3,cmap=’viridis’)
相关图(correllogram
# Import Dataset
df = pd.read_csv("mtcars.csv")
# Plot
plt.figure(figsize=(12,10), dpi= 80)
sns.(), ().columns, ().columns, cmap='RdYlGn', center=0, annot=True)
# Decorations
plt.title('Correlogram of mtcars', fontsize=22)
icks(fontsize=12)
icks(fontsize=12)
plt.show()
面积图(area chart)
案例:
import numpy as np
import pandas as pd
# Prepare Data
df = pd.read_csv("onomics.csv", parse_dates=['date']).head(100)
x = np.arange(df.shape[0])
y_returns = (df.psavert.diff().fillna(0)/df.psavert.shift(1)).fillna(0) * 100
# Plot
plt.figure(figsize=(16,10), dpi= 80)
plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] >= 0, facecolor='green', interpolate=True, alpha=0.7)
plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] <= 0, facecolor='red', interpolate=True, alpha=0.7)
# Annotate
plt.annotate('Peak \n1975', xy=(94.0, 21.0), xytext=(88.0, 28),
            bbox=dict(boxstyle='square', fc='firebrick'),
            arrowprops=dict(facecolor='steelblue', shrink=0.05), fontsize=15, color='white')
# Decorations
xtickvals = [str(m)[:3].upper()+"-"+str(y) for y,m in zip(df.ar, df.h_name())]
a().set_xticks(x[::6])
a().set_xticklabels(xtickvals[::6], rotation=90, fontdict={'horizontalalignment': 'center', 'verticalalignment': 'center_baseline'})
plt.ylim(-35,35)
plt.xlim(1,100)
plt.title("Month Economics Return %", fontsize=22)
plt.ylabel('Monthly returns %')
id(alpha=0.5)
plt.show()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。