Python利用matplotlib画出漂亮的分析图表
作者:机器学习初学者 时间:2023-03-04 01:10:09
前言
作为一名优秀的分析师,还是得学会一些让图表漂亮的技巧,这样子拿出去才更加有面子哈哈。好了,今天的锦囊就是介绍一下各种常见的图表,可以怎么来画吧。
数据集引入
首先引入数据集,我们还用一样的数据集吧,分别是 Salary_Ranges_by_Job_Classification
以及 GlobalLandTemperaturesByCity
。(具体数据集可以后台回复 plot
获取)
# 导入一些常用包
import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('fivethirtyeight')
#解决中文显示问题,Mac
from matplotlib.font_manager import FontProperties
# 查看本机plt的有效style
print(plt.style.available)
# 根据本机available的style,选择其中一个,因为之前知道ggplot很好看,所以我选择了它
mpl.style.use(['ggplot'])
# ['_classic_test', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2']
# 数据集导入
# 引入第 1 个数据集 Salary_Ranges_by_Job_Classification
salary_ranges = pd.read_csv('./data/Salary_Ranges_by_Job_Classification.csv')
# 引入第 2 个数据集 GlobalLandTemperaturesByCity
climate = pd.read_csv('./data/GlobalLandTemperaturesByCity.csv')
# 移除缺失值
climate.dropna(axis=0, inplace=True)
# 只看中国
# 日期转换, 将dt 转换为日期,取年份, 注意map的用法
climate['dt'] = pd.to_datetime(climate['dt'])
climate['year'] = climate['dt'].map(lambda value: value.year)
climate_sub_china = climate.loc[climate['Country'] == 'China']
climate_sub_china['Century'] = climate_sub_china['year'].map(lambda x:int(x/100 +1))
climate.head()
折线图
折线图是比较简单的图表了,也没有什么好优化的,颜色看起来顺眼就好了。下面是从网上找到了颜色表,可以从中挑选~
# 选择上海部分天气数据
df1 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.set_index('dt')
df1.head()
# 折线图
df1.plot(colors=['lime'])
plt.title('AverageTemperature Of ShangHai')
plt.ylabel('Number of immigrants')
plt.xlabel('Years')
plt.show()
上面这是单条折线图,多条折线图也是可以画的,只需要多增加几列。
# 多条折线图
df1 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SH'})
df2 = climate.loc[(climate['Country']=='China')&(climate['City']=='Tianjin')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'TJ'})
df3 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shenyang')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SY'})
# 合并
df123 = df1.merge(df2, how='inner', on=['dt'])\
.merge(df3, how='inner', on=['dt'])\
.set_index(['dt'])
df123.head()
# 多条折线图
df123.plot()
plt.title('AverageTemperature Of 3 City')
plt.ylabel('Number of immigrants')
plt.xlabel('Years')
plt.show()
饼图
接下来是画饼图,我们可以优化的点多了一些,比如说从饼块的分离程度,我们先画一个“低配版”的饼图。
df1 = salary_ranges.groupby('SetID', axis=0).sum()
# “低配版”饼图
df1['Step'].plot(kind='pie', figsize=(7,7),
autopct='%1.1f%%',
shadow=True)
plt.axis('equal')
plt.show()
# “高配版”饼图
colors = ['lightgreen', 'lightblue'] #控制饼图颜色 ['lightgreen', 'lightblue', 'pink', 'purple', 'grey', 'gold']
explode=[0, 0.2] #控制饼图分离状态,越大越分离
df1['Step'].plot(kind='pie', figsize=(7, 7),
autopct = '%1.1f%%', startangle=90,
shadow=True, labels=None, pctdistance=1.12, colors=colors, explode = explode)
plt.axis('equal')
plt.legend(labels=df1.index, loc='upper right', fontsize=14)
plt.show()
散点图
散点图可以优化的地方比较少了,ggplot2的配色都蛮好看的,正所谓style选的好,省很多功夫!
# 选择上海部分天气数据
df1 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SH'})
df2 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shenyang')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SY'})
# 合并
df12 = df1.merge(df2, how='inner', on=['dt'])
df12.head()
# 散点图
df12.plot(kind='scatter', x='SH', y='SY', figsize=(10, 6), color='darkred')
plt.title('Average Temperature Between ShangHai - ShenYang')
plt.xlabel('ShangHai')
plt.ylabel('ShenYang')
plt.show()
面积图
# 多条折线图
df1 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SH'})
df2 = climate.loc[(climate['Country']=='China')&(climate['City']=='Tianjin')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'TJ'})
df3 = climate.loc[(climate['Country']=='China')&(climate['City']=='Shenyang')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.rename(columns={'AverageTemperature':'SY'})
# 合并
df123 = df1.merge(df2, how='inner', on=['dt'])\
.merge(df3, how='inner', on=['dt'])\
.set_index(['dt'])
df123.head()
colors = ['red', 'pink', 'blue'] #控制饼图颜色 ['lightgreen', 'lightblue', 'pink', 'purple', 'grey', 'gold']
df123.plot(kind='area', stacked=False,
figsize=(20, 10), colors=colors)
plt.title('AverageTemperature Of 3 City')
plt.ylabel('AverageTemperature')
plt.xlabel('Years')
plt.show()
直方图
# 选择上海部分天气数据
df = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.set_index('dt')
df.head()
# 最简单的直方图
df['AverageTemperature'].plot(kind='hist', figsize=(8,5), colors=['grey'])
plt.title('ShangHai AverageTemperature Of 2010-2013') # add a title to the histogram
plt.ylabel('Number of month') # add y-label
plt.xlabel('AverageTemperature') # add x-label
plt.show()
条形图
# 选择上海部分天气数据
df = climate.loc[(climate['Country']=='China')&(climate['City']=='Shanghai')&(climate['dt']>='2010-01-01')]\
.loc[:,['dt','AverageTemperature']]\
.set_index('dt')
df.head()
df.plot(kind='bar', figsize = (10, 6))
plt.xlabel('Month')
plt.ylabel('AverageTemperature')
plt.title('AverageTemperature of shanghai')
plt.show()
df.plot(kind='barh', figsize=(12, 16), color='steelblue')
plt.xlabel('AverageTemperature')
plt.ylabel('Month')
plt.title('AverageTemperature of shanghai')
plt.show()
来源:https://blog.51cto.com/u_15671528/5429295
标签:Python,matplotlib,绘制,分析,图表
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python list和numpy array的存储和读取方法
2022-05-04 05:58:10
![](https://img.aspxhome.com/file/2023/2/115462_0s.jpg)
简单了解python模块概念
2023-03-21 19:38:46
深入理解Python虚拟机中描述器的实现原理
2021-08-05 21:20:48
安装Mysql时可能会遇到的一些疑难杂症
2024-01-28 13:30:09
![](https://img.aspxhome.com/file/2023/2/65702_0s.png)
通过Jython调用Python脚本的实现方法
2022-07-08 23:21:42
![](https://img.aspxhome.com/file/2023/6/64656_0s.png)
Python利用heapq实现一个优先级队列的方法
2021-08-05 06:28:48
![](https://img.aspxhome.com/file/2023/6/89446_0s.jpg)
用SQL语句完成SQL Server数据库的修复
2008-11-24 20:49:00
使用Python的Django框架结合jQuery实现AJAX购物车页面
2023-05-21 01:59:28
![](https://img.aspxhome.com/file/2023/3/99033_0s.jpg)
IE下修改<p>标签的innerHTML出错
2007-11-11 10:12:00
go goroutine 怎样进行错误处理
2024-05-22 10:14:39
Go语言高效编程的3个技巧总结
2024-02-03 02:52:38
MySQL触发器trigger的使用
2024-01-23 15:08:23
![](https://img.aspxhome.com/file/2023/1/114031_0s.png)
Python自动生产表情包
2022-04-13 05:25:36
![](https://img.aspxhome.com/file/2023/0/81470_0s.jpg)
asp.net实现存储和读取数据库图片
2024-01-19 06:56:32
![](https://img.aspxhome.com/file/2023/8/83208_0s.png)
将设计执行到底—记Qzone项目组视觉设计标注的前前后后
2009-04-19 13:22:00
![](https://img.aspxhome.com/file/UploadPic/20094/19/892_banner-85s.jpg)
Python 中使用 argparse 解析命令行参数
2023-10-26 14:10:42
解析如何加快mysql编译的速度
2024-01-15 07:26:55
记一次MySQL更新语句update的踩坑
2024-01-16 19:35:29
Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)
2023-08-26 16:08:33
Oracle数据安全面面观
2024-01-20 02:12:38