完整的Python Matplotlib的教程

所使用的的数据集
链接:https://pan.baidu.com/s/1LW-km_5nGh6SVFm7kgnxCQ
提取码:nyhd

导入相关的包 Load Necessary Libraries

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Basic Graph

1.plot折线图

#plot折线图
# 创建数据
x=[0,1,2,3,4,5];y=[0,2,4,6,8,10]

# Resize your Graph(dpi specifies pixels per inch. When saving probably should use 300 if possible)
# 调整图的大小
plt.figure(figsize=(5,3), dpi=100)

## Line 1
# Keyword Argument Notation plot 相关参数
plt.plot(x, y, label='2x', color='green', linestyle='dashed', linewidth = 2, marker='o', markersize=12, markeredgecolor='blue')

# use shorthand notation 简化画图
# fmt = '[color][marker][line]'
# plt.plot(x,y,'b^--',label='2x')

## Line 2
# select interval we want to plot points at选取点
x2= np.arange(0,4.5,0.5) # x2=[0,0.5,1,1.5,2,2.5,3,3.5,4]

# Plot part of the graph as line 取一部分画成直线
plt.plot(x2[:6],x2[:6]**2,'r',label='x^2')
# Plot remainder of graph as dot 取另一部分画成点线
plt.plot(x2[5:],x2[5:]**2,'r--')

# Add a title (specify font parameters with fontdict) 标题
plt.title('My first Graph',fontdict={'fontname':'Comic Sans MS','fontsize':20})

# X and Y labels 横纵坐标
plt.xlabel('X Axis',fontdict={'fontname':'Arial','fontsize':10})
plt.ylabel('Y Axis')

# X, Y axis Tickmarks (scale of your graph) 横纵坐标的刻度
plt.xticks([0,1,2,3,4,5])
plt.yticks([0,2,4,6,8,10]) #横纵坐标轴的刻度显示

# Add a legend 添加图例
plt.legend()

# Save figure(dpi 300 is good when saving so graph has high resolution) 保存图片
plt.savefig('mygraph.png', dpi=300)

# Show plot 显示图片
plt.show()

运行结果:
plot折线图

2.bar条形图

labels = ['A', 'B', 'C']
values = [1,4,2]

bars = plt.bar(labels, values)

patterns = ['/', 'O', '*']
for bar in bars:
    bar.set_hatch(patterns.pop(0))

#bars[0].set_hatch('/')
#bars[1].set_hatch('O')
#bars[2].set_hatch('*')

plt.xlabel('X Axis',fontdict={'fontname':'Arial','fontsize':10})
plt.ylabel('Y Axis')
plt.title('My Second Graph',fontdict={'fontname':'Comic Sans MS','fontsize':22})
plt.figure(figsize=(6,4))

plt.show()

运行结果:
bar条形图

Real World Example导入真实数据进行分析

【以fifa_data.csv 和 gas_prices.csv 为例】

Load Fifa Data加载数据

gas_prices.csv:

gas = pd.read_csv('gas_prices.csv')
print(gas.head(6))

在这里插入图片描述
fifa_data.csv:

fifa = pd.read_csv('fifa_data.csv')
fifa

在这里插入图片描述

Plot折线图

gas = pd.read_csv('gas_prices.csv')

plt.figure(figsize=(8,5))
plt.plot(gas.Year, gas.USA, 'r.-',label='USA')
plt.plot(gas['Year'], gas['Canada'], 'b.-',label='Canada')

# Another Way to plot many values!
#countries_to_look_at = ['Australia','USA','Canada','South Korea']
#for country in gas:
#    if country in countries_to_look_at:
#        plt.plot(gas.Year, gas[country], marker='.',label=country )
        
plt.title('USA vs Canada Gas Prices', fontdict = {'fontsize':18})
plt.ylabel('Dollar/Gallon')

#plt.xticks(gas.Year)
plt.xticks(gas.Year[::3])
#plt.plt.xticks(gas.Year[::3].tolist() + [2011])

plt.legend()

plt.savefig('Gas_price_figure.png', dpi=300)
plt.show()

在这里插入图片描述

Histograms直方图

bins=[40,50,60,70,80,90,100]

plt.hist(fifa.Overall,bins=bins,color='#83f442') #color picker

plt.xticks(bins)

plt.xlabel('Skill Level')
plt.ylabel('Number of Players')
plt.title('Distribution of Player Skills in FIFA 2018')

plt.yticks([0,100])

plt.show()

在这里插入图片描述

pie饼图

left = fifa.loc[fifa['Preferred Foot'] == 'Left'].count()[0]
right = fifa.loc[fifa['Preferred Foot'] == 'Right'].count()[0]

labels=['Left','Right']
colors=['#abcdef', '#aabbcc']
plt.pie([left,right], labels = labels, colors = colors, autopct = '%.2f %%')

plt.title('Foot Preference of FIFA Players')

plt.show()

在这里插入图片描述

print(fifa.Weight)
fifa.Weight = [int(x.strip('lbs')) if type(x)==str else x for x in fifa.Weight]
print(fifa.Weight)

plt.style.use('ggplot')

light = fifa.loc[fifa.Weight < 125].count()[0]
light_medium = fifa.loc[(fifa.Weight >= 125) & (fifa.Weight <150)].count()[0]
medium = fifa[(fifa.Weight >= 150) & (fifa.Weight <175)].count()[0]
medium_heavy = fifa[(fifa.Weight >= 175) & (fifa.Weight <200)].count()[0]
heavy = fifa[fifa.Weight >200].count()[0]
labels = ['Under 125','125-150','150-175','175-200','Over200']
weights = [light, light_medium, medium, medium_heavy, heavy]
explode = (.4,.2,.1,.1,.4) #外扩
plt.title('Weight Distribution of FIFA Players(in lbs)')
plt.pie(weights, labels= labels, autopct='%.2f %%', pctdistance = 0.8, explode = explode)
plt.show()

在这里插入图片描述

box箱图

plt.style.use('seaborn')

plt.figure(figsize=(5,8))
barcelona = fifa.loc[fifa.Club == 'FC Barcelona']['Overall']
madrid = fifa.loc[fifa.Club == 'Real Madrid']['Overall']
revs = fifa.loc[fifa.Club == 'New England Revolution']['Overall']

labels = ['FC Bracelona', 'Real Madrid','New England Revolution']

boxes = plt.boxplot([barcelona, madrid, revs], labels=labels,patch_artist=True, medianprops={'linewidth':2})

for box in boxes['boxes']:
    # Set edge color
    box.set(color = '#4286f4', linewidth = 2)
    
    # Change Fill Color
    box.set(facecolor = '#e0e0e0')
plt.title('Professional Soccer Team Comparison')
plt.ylabel('FIFA Overall Rating')

plt.show()

在这里插入图片描述

参考链接:
https://www.bilibili.com/video/BV1sV411t7Gw?p=4

Matplotlib 最具价值的50个可视化项目:
https://www.heywhale.com/mw/project/5f4b3f146476cf0036f7e51e

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Python Matplotlib教程是一种介绍如何使用Python Matplotlib库进行数据可视化的教程Matplotlib是一种流行的Python库,用于创建各种类型的图表和可视化。该教程将介绍Matplotlib的基础知识,包括如何创建简单的图表,如何自定义图表的外观和样式,以及如何使用Matplotlib进行数据分析和可视化。此外,该教程还将介绍如何使用Matplotlib与其他Python库进行交互,如NumPy和Pandas。 ### 回答2: matplotlib是一个用于制作图形和图表的Python库。它提供了一个方便易用的绘图接口,可以用于展示数据和分析结果。 在使用matplotlib之前,首先需要安装matplotlib库。可以通过pip或conda进行安装。 学习matplotlib的第一步是了解基本的绘图概念和基本的绘图函数。常用的绘图函数包括plot、scatter、bar等,它们可以用于绘制线图、散点图和柱状图。 在编写绘图代码之前,需要导入matplotlib库。一般使用以下代码导入matplotlib: ```python import matplotlib.pyplot as plt ``` 然后通过调用相应的绘图函数生成图像。例如,使用plot函数绘制线图,可以通过以下代码实现: ```python x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) plt.show() ``` 上述代码会生成一个包含直线的图像,x轴表示x的取值,y轴表示y的取值。 除了基本的绘图函数,matplotlib还提供了丰富的参数和选项,用于自定义图像的样式和外观。例如,可以设置坐标轴的标签、标题、图例等。 此外,matplotlib还支持多子图布局、保存图像等功能。可以通过subplot函数实现多个子图的绘制。 此外,matplotlib还支持与NumPy和Pandas等常用数据处理库的集成,可以直接绘制这些库中的数据。 总之,学习matplotlib可以帮助我们更好地展示数据和分析结果,使得图表更加直观和易于理解。掌握基本的绘图函数和参数,可以满足日常数据可视化的需求。 ### 回答3: Pythonmatplotlib是一个用于绘制图表和可视化数据的库。它是一个功能强大、灵活且易于使用的工具,适用于各种绘图需求。 matplotlib提供了一个类似于MATLAB的界面,可以轻松地创建各种类型的图表,如线图、散点图、直方图、饼图等。它还支持添加图例、坐标轴标签、标题等,使得图表更具可读性和吸引力。 使用matplotlib,您可以通过简单的几行代码创建一个基本图表。首先,您需要导入matplotlib库以及所需的模块,比如pyplot。然后,使用plot函数传递数据数组即可创建一个线图。您还可以使用其他函数和参数来对图表进行定制,如设置线条颜色、添加网格线、调整坐标轴范围等。 除了基本的绘图功能,matplotlib还提供了许多高级功能,如3D绘图、动画、图像处理等。您可以使用这些功能来创建更复杂的图表,并展示更多的细节和信息。 在使用matplotlib之前,您可能需要安装它,可以通过命令`pip install matplotlib`来安装。然后,您可以在Python代码中导入matplotlib库,并开始使用它的功能。 另外,matplotlib还有一个强大的社区支持,提供了丰富的文档、教程和示例代码,这些资源可以帮助您快速上手和解决问题。 总而言之,matplotlib是一个功能丰富且易于使用的库,可以帮助您轻松地创建图表和可视化数据。无论您是初学者还是有经验的开发者,都可以从matplotlib中受益,并将其应用于各种数据分析和可视化任务中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来包番茄沙司

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值