机器学习 - Python Matplotlib 练习, 常见功能查阅

机器学习记录

Matplotlib

引入库

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# data from: https://github.com/KeithGalli/matplotlib_tutorial
data_dir = "/data_dir"

.plot()

x = [0, 1, 2, 3, 4, 5]
y = [0, 2, 4, 6, 8, 10]

# 设置图片大小
plt.figure(figsize=(5, 3), dpi=300)

# plt.plot(x, y,
#          label='label legend',
#          color='red',
#          linewidth=2,
#          marker='x',
#          markersize=8,
#          markeredgecolor='blue',
#          linestyle='--'
#         )
plt.plot(x, y,
         'r^-.',
         label='2x'
        )

x2 = np.arange(0, 5, 0.5)
plt.plot(x2, x2**2, 'b', label='X^2')
plt.plot(x2[:6], x2[:6]**3, 'g', label='X^3')
plt.plot(x2[5:], x2[5:]**3, 'y--', label='X^3')

plt.title('First Graph!', fontdict={'fontsize': 20})

# 设置坐标轴
plt.xlabel('X Axis')
plt.ylabel('Y Axis')

# 设置显示的坐标
# plt.xticks([0, 1, 2, 5])
# plt.yticks([0, 1, 2, 10, 20])

# 说明
plt.legend()

# plt.savefig('./python-matplotlib.001.png', dpi=600)

plt.show()

在这里插入图片描述

.bar()

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

# 这个要放在前面
plt.figure(figsize=(6, 2), dpi=300)

bars = plt.bar(labels, values)
bars[0].set_hatch('/')
bars[1].set_hatch('.')
bars[2].set_hatch('o')

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5UAwBqRp-1682233614929)(../images/python-matplotlib.001/output_6_0.png)]

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

# 这个要放在前面
plt.figure(figsize=(6, 2), dpi=300)

bars = plt.bar(labels, values)

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

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G1Yy1QZ2-1682233614929)(../images/python-matplotlib.001/output_7_0.png)]

df = pd.read_csv(f'{data_dir}/matplotlib_tutorial/gas_prices.csv')
df = df.sort_values('Year')
print(df.head())

plt.figure(figsize=(8, 5))

# 只展示以下国家的数据
countries_to_look_at = ['Australia', 'USA']

for country in df:
#     if country != 'Year':
    if country in countries_to_look_at:
        plt.plot(df.Year, df[country], marker='.', label=country)

plt.title('Gass Prices over time (in USD)', fontdict={'fontsize': 18, 'fontweight': 'bold'})
plt.xlabel('Year')
plt.ylabel('US Dollars')

plt.xticks(df.Year[::3].tolist() + [2011])
        
plt.legend()

# plt.savefig('./python-matplotlib.002.png', dpi=300)

plt.show()
   Year  Australia  Canada  France  Germany  Italy  Japan  Mexico  \
0  1990        NaN    1.87    3.63     2.65   4.59   3.16    1.00   
1  1991       1.96    1.92    3.45     2.90   4.50   3.46    1.30   
2  1992       1.89    1.73    3.56     3.27   4.53   3.58    1.50   
3  1993       1.73    1.57    3.41     3.07   3.68   4.16    1.56   
4  1994       1.84    1.45    3.59     3.52   3.70   4.36    1.48   

   South Korea    UK   USA  
0         2.05  2.82  1.16  
1         2.49  3.01  1.14  
2         2.65  3.06  1.13  
3         2.88  2.84  1.11  
4         2.87  2.99  1.11  

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HQj4xs7S-1682233614929)(../images/python-matplotlib.001/output_9_1.png)]

df = pd.read_csv(f'{data_dir}/matplotlib_tutorial/fifa_data.csv')
print(df.head())
   Unnamed: 0      ID               Name  Age  \
0           0  158023           L. Messi   31   
1           1   20801  Cristiano Ronaldo   33   
2           2  190871          Neymar Jr   26   
3           3  193080             De Gea   27   
4           4  192985       K. De Bruyne   27   

                                            Photo Nationality  \
0  https://cdn.sofifa.org/players/4/19/158023.png   Argentina   
1   https://cdn.sofifa.org/players/4/19/20801.png    Portugal   
2  https://cdn.sofifa.org/players/4/19/190871.png      Brazil   
3  https://cdn.sofifa.org/players/4/19/193080.png       Spain   
4  https://cdn.sofifa.org/players/4/19/192985.png     Belgium   

                                  Flag  Overall  Potential  \
0  https://cdn.sofifa.org/flags/52.png       94         94   
1  https://cdn.sofifa.org/flags/38.png       94         94   
2  https://cdn.sofifa.org/flags/54.png       92         93   
3  https://cdn.sofifa.org/flags/45.png       91         93   
4   https://cdn.sofifa.org/flags/7.png       91         92   

                  Club  ... Composure Marking StandingTackle  SlidingTackle  \
0         FC Barcelona  ...      96.0    33.0           28.0           26.0   
1             Juventus  ...      95.0    28.0           31.0           23.0   
2  Paris Saint-Germain  ...      94.0    27.0           24.0           33.0   
3    Manchester United  ...      68.0    15.0           21.0           13.0   
4      Manchester City  ...      88.0    68.0           58.0           51.0   

  GKDiving  GKHandling  GKKicking  GKPositioning GKReflexes Release Clause  
0      6.0        11.0       15.0           14.0        8.0        €226.5M  
1      7.0        11.0       15.0           14.0       11.0        €127.1M  
2      9.0         9.0       15.0           15.0       11.0        €228.1M  
3     90.0        85.0       87.0           88.0       94.0        €138.6M  
4     15.0        13.0        5.0           10.0       13.0        €196.4M  

[5 rows x 89 columns]
bins = np.arange(40, 100, 10)
plt.hist(df.Overall)
plt.hist(df.Overall, bins=bins, color='#0abcde')

plt.xticks(bins)

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

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YdG6T82K-1682233614930)(../images/python-matplotlib.001/output_11_0.png)]

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

labels = ['Left', 'Right']
colors = ['#ababab', '#cdcdcd']

plt.pie(
    [left, right],
    labels=labels,
    colors=colors,
    autopct='%.2f'
)

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

plt.show()
4211
13948

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z3Vi6inq-1682233614930)(../images/python-matplotlib.001/output_12_1.png)]

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

light = df.loc[df.Weight < 125].count()[0]
light_medium = df.loc[(df.Weight >= 125) & (df.Weight < 150)].count()[0]
medium = df.loc[(df.Weight >= 150) & (df.Weight < 175)].count()[0]
medium_heavy = df.loc[(df.Weight >= 175) & (df.Weight < 200)].count()[0]
heavy = df.loc[df.Weight >= 200].count()[0]

# plt.style.use('default')
plt.style.use('ggplot')

weights = [light, light_medium, medium, medium_heavy, heavy]
labels = ['Under 125', '125-150', '150-175', '175-200', 'Over 200']
explode = (.4, .2, 0, 0, .4)

plt.title('Weight Distribution of FIFA Players (in lbs)')

# pctdistance 百分比显示的位置离圆心的距离, 半径的 百分比
# explode 块是否有空白间隙
plt.pie(
    weights,
    labels=labels,
    autopct='%.2f',
    pctdistance=.8,
    explode=explode
)

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LDu4BV9f-1682233614930)(../images/python-matplotlib.001/output_13_0.png)]

barcelona = df.loc[df.Club == 'FC Barcelona']['Overall']
madrid = df.loc[df.Club == 'Real Madrid']['Overall']
revs = df.loc[df.Club == 'New England Revolution']['Overall']

plt.figure(figsize=(6, 8))

plt.style.use('default')
# plt.style.use('ggplot')

labels = ['FC Barcelona', 'Real Madrid', 'New England Revolution']
plt.title('Professional Soccer Team Comparison')
plt.ylabel('FIFA Overall Rating')

boxes = plt.boxplot(
    [barcelona, madrid, revs],
    labels=labels,
    patch_artist=True
)

for box in boxes['boxes']:
#     设置方框的样式
    box.set(color='#ff0000', linewidth=2)
#     设置填充的样式, 要设置 patch_artist=True
    box.set(facecolor='#00ff00')

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lDPJTmHL-1682233614931)(../images/python-matplotlib.001/output_14_0.png)]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值