目录:
4.5 完善统计图形
(1)图例和画布使用
图例中legend中loc中的位置和数字关系的使用:
- best:0
- upper right:1
- upper left:2
- lower left:3
- lower right:4
- right:5
- center left:6
- center right:7
(2)图形添加内容
4.6 图像样式高级操作
(1)绘制双坐标轴
import pandas as pd
import matplotlib.pyplot as plt
import os
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
data = pd.read_csv('supermarket_sales.csv')
data_1 = data.groupby('Date').mean()
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(data_1.index, data_1.cogs, color='blue', label='cogs')
plt.legend(loc='upper left')
ax1.set_ylabel('情况1')
ax2 = ax1.twinx()
ax2.plot(data_1.index, data_1.Rating, color='red', label='Rating')
ax2.set_ylabel('情况2')
plt.legend(loc='upper center')
plt.show()
(2)多个图形合并
import pandas as pd
import matplotlib.pyplot as plt
import os
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
GDP_data = pd.read_csv('gdp_csv.csv')[:40]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(16, 9))
plt.subplot(121)
plt.plot(GDP_data['Year'], GDP_data['Value'], c='c')
plt.xlabel('年份', fontsize=12)
plt.ylabel('GDP', fontsize=18)
plt.xticks(rotation=45)
plt.subplot(122)
plt.bar(x=GDP_data.Year, height=GDP_data.Value, color='r')
plt.show()
4.7 高级绘图
(1)Seaborn基础
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
GDP = pd.read_csv('gdp_csv.csv')[:49]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 第一种调用方式
plt.style.use('seaborn')
plt.bar(x=GDP.Year, height=GDP.Value, tick_label=GDP.Year, color='steelblue')
plt.xticks(rotation=45)
plt.ylabel('GDP')
plt.show()
# 第二种调用方式
sns.set(style='darkgrid', context='notebook', font_scale=1.2)
plt.bar(x=GDP.index, height=GDP.Value, tick_label=GDP.Year, color='steelblue')
plt.xticks(rotation=45)
plt.ylabel('GDP')
plt.show()
# 第三种调用方式
sns.barplot(x='Year', y='Value', data=GDP, color='steelblue', orient='vertical')
plt.xticks(rotation=45)
plt.show()
(2)绘制常用统计图形
1. 柱状图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
GDP = pd.read_csv('gdp_csv.csv')[:49]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.barplot(x='Year', y='Value', hue='Country Code', data=GDP, palette='husl', orient='v')
plt.ylabel('GDP')
plt.legend(bbox_to_anchor=(1.01, 0.85), ncol=1, frameon=False)
plt.show()
2. 散点图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
Iris = pd.read_csv('Iris.csv')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.scatterplot(x='SepalWidthCm', y='SepalLengthCm', data=Iris, color='red', markers='+', s=20)
plt.xlabel('花瓣宽度')
plt.ylabel('花瓣长度')
plt.show()
3. 箱线图
① 单个箱线图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
Titanic = pd.read_csv('train_and_test2.csv')
Titanic.dropna(subset=['Age'], inplace=True)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.boxplot(y='Age', data=Titanic, showmeans=True, color='steelblue', width=0.3)
plt.xticks(fontsize=12, rotation=45)
plt.show()
② 多个箱线图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
sec_building = pd.read_csv('buildings.csv')
group_buildingtype = sec_building.groupby('buildingtype')
avg_price = group_buildingtype.agg({'2018energyusintensity': np.mean}).sort_values('2018energyusintensity', ascending=False)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(12, 8))
sns.boxplot(x='buildingtype', y='2018energyusintensity', data=sec_building, order=avg_price.index, showmeans=True,
color='steelblue', width=0.3)
plt.ylabel('单价')
plt.title('比较')
plt.xticks(rotation=45, fontsize=10)
plt.show()
4. 直方图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
from scipy.stats import norm
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
Titanic = pd.read_csv('train_and_test2.csv')
Age_Male = Titanic[Titanic.Sex == 0]['Age']
Age_Female = Titanic[Titanic.Sex == 1]['Age']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.distplot(Age_Male, bins=30, kde=False, hist_kws={'color': 'steelblue'}, norm_hist=True, label='男性')
sns.distplot(Age_Male, hist=False, kde=False, fit=norm, fit_kws={'color': 'yellow'}, norm_hist=True, label='男性正态分布图')
sns.distplot(Age_Female, bins=30, kde=False, hist_kws={'color': 'red'}, norm_hist=True, label='女性')
sns.distplot(Age_Female, hist=False, kde=False, fit=norm, fit_kws={'color': 'green'}, norm_hist=True, label='女性正态分布图')
plt.legend(loc='best')
plt.show()
5. 折线图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
Titanic = pd.read_csv('train_and_test2.csv')
sns.set(style='ticks', context='notebook')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.lineplot(x='Passengerid', y='Fare', data=Titanic, lw=2, color='red')
plt.xticks(rotation=45)
plt.show()
6. 回归图
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
os.chdir(r'C:\Users\Administrator.DESKTOP-0L8IC5U\Desktop\数据分析\data')
iris = pd.read_csv('Iris.csv')
sns.lmplot(x='SepalLengthCm', y='SepalWidthCm', data=iris, legend_out=False, markers='o', fit_reg=True, aspect=1.3, height=8)
plt.show()
4.8 精美制图
(1)plotly基础
在真实项目中,使用plotly绘图模块进行绘图的完整流程包括:
- 添加图轨信息,例如使用Scatter函数
- 设置画图布局,使用layout命令
- 集成图形、布局数据
- 绘制图形的输出,命令是offline.plot
import plotly as py
from plotly.graph_objs import Scatter
trace0 = Scatter(x=[1, 2, 3, 4], y=[10, 15, 13, 17])
trace1 = Scatter(x=[1, 2, 3, 4], y=[6, 5, 11, 9])
data = [trace0, trace1]
py.offline.plot(data, filename='fth.html')
(2)常见图形绘制
1. 散点图
数据:
违代码:
import plotly as py
from plotly.graph_objs import Scatter
pyplot = py.offline.iplot()
trace1 = Scatter(x=income_tax['year'], y=income_tax['x2'], mode='markers', name='在职员工工资总收入')
trace2 = Scatter(x=income_tax['year'], y=income_tax['x3'], mode='lines', name='社会消费品零售总额')
trace3 = Scatter(x=income_tax['year'], y=income_tax['x8'], mode='markers+lines', name='地区生产总值')
data = [trace1, trace2, trace3]
pyplot(data)
结果:
2. 折线图
违代码:
import plotly as py
from plotly.graph_objs import Scatter
import plotly.graph_objs as go
pyplot = py.offline.iplot()
trace1 = Scatter(x=income_tax['x8'], y=income_tax['y'], name='地区生产总值和财政收入关系', mode='lines',
line=dict(width=2, color='green'))
trace2 = Scatter(x=income_tax['x3'], y=income_tax['y'], name='社会消费品零售总额和财政收入关系', mode='lines',
line=dict(width=2, color='blue'))
data = [trace1, trace2]
layout = go.Layout(title='财政收入变化', xaxis=dict(title='地区生产总值'), yaxis=dict(title='财政收入'),
legend=dict(x=1, y=0.5, font=dict(size=5, color='black')))
fig = go.Figure(data=data, layout=layout)
pyplot(fig)
3. 柱状图
柱状图违代码:
import plotly as py
import plotly.graph_objs as go
pyplot = py.offline.iplot()
trace_basic = [go.Bar(x=order_region.index.tolist(), y=order_region.values.tolist(),
marker=dict(color=['red', 'blue', 'darkgray', 'darkblue']), opacity=0.39)]
layout = go.Layout(title='不同地区订单数量', xaxis=dict(title='地区'))
figure_basic = go.Figure(data=trace_basic, layout=layout)
pyplot(figure_basic)
堆叠柱状图伪代码:
import plotly as py
import plotly.graph_objs as go
pyplot = py.offline.iplot()
G1 = industry_gdp[industry_gdp['industry_type'] == '第一产业']
G2 = industry_gdp[industry_gdp['industry_type'] == '第二产业']
G3 = industry_gdp[industry_gdp['industry_type'] == '第三产业']
trace1 = go.Bar(x=G1.quarter, y=G1['GDP'], name='第一产业')
trace2 = go.Bar(x=G2.quarter, y=G2['GDP'], name='第二产业')
trace3 = go.Bar(x=G3.quarter, y=G3['GDP'], name='第三产业')
trace = [trace1, trace2, trace3]
layout = go.Layout(title='三大产业GDP', xaxis=dict(title='季度'), barmode='stack')
figure_basic = go.Figure(data=trace, layout=layout)
pyplot(figure_basic)
4. 直方图
伪代码:
import plotly as py
import plotly.graph_objs as go
pyplot = py.offline.iplot()
data = [go.Histogram(x=Titanic['Age'], histnorm='probability', marker=dict(color='blue'))]
pyplot(data)
5. 饼图
伪代码:
import plotly as py
import plotly.graph_objs as go
pyplot = py.offline.iplot()
trace = [go.Pie(labels=order_region.index.tolist(), values=order_region.values.tolist(), hole=0.2,
textfont=dict(size=12, color='white'))]
layout = go.Layout(title='不同地区订单')
fig = go.Figure(data=trace, Layout=layout)
pyplot(fig)