Matplotlib双Y轴折线图小实例

2020-03-03 14:28:37 浏览数 (1)

本文内容为重复 Learning Python: Part 2 - Visualizing the NBA Draft 教程的第二部分内容

简单注释

fig,ax1 = plt.subplots(figsize=(12,9))创建画布,有点类似于ggplot2的ggplot()函数的作用;figsize参数用来控制图片长和宽,但是单位是啥还没搞明白

plt.title()添加标题

plt.grid()添加网格axis参数指定坐标轴

plt.tick_params()可以控制坐标轴刻度标签字体大小labelsize 大小axis坐标轴

ax1.set_ylabel()坐标轴标签

ax1.set_ylim()坐标轴范围

ax1.legend()图例;loc参数指点图例位置;其他参数还需要仔细研究一下

ax1.set_yticks(0,10,5)坐标轴如何分割

ax1.spines["top"].set_visible(False)边框

ax1.twinx()生成另外一个坐标轴

fig.text(0.1,0.02,"Text")添加文本内容

小例子
代码语言:javascript复制
import matplotlib.pyplot as plt
import numpy as np

A = ["a","b","c","d","e"]
B = [5,4,6,3,4]
fig, ax1 = plt.subplots(figsize=(12,9))
ax1.plot(A,B,label="Practice")
plt.title("Example")
ax1.legend()
ax1.grid(axis="y",color="grey",linestyle="--",alpha=0.5)
ax1.tick_params(axis="x",labelsize=30)
ax1.tick_params(axis="y",labelsize=20)
ax1.set_ylabel("Y",fontsize = 18)
ax1.set_xlabel("X",fontsize = 20)
ax1.set_ylim(0,15)
ax1.set_yticks(np.linspace(0,15,16))
for tl in ax1.get_yticklabels():
    tl.set_color('r')

ax1.spines['top'].set_visible(False)
fig.text(0.1,0.02,"Author:MingYan")
plt.savefig("Practice.png")

Practice.png

双Y轴折线图

(plot both of those plots in one plot with 2 y-axis labels) 一个Y轴用来展示每年选秀总人数,另一个Y轴用来展示赢球贡献值的平均值。

导入需要的模块、读入数据
(如需要下文用到的数据,可至公众号后台回复管检测 选秀)
代码语言:javascript复制
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


draft_df = pd.read_csv("draft_data_1996_to_2014.csv",index_col=0)

X_values = draft_df.Draft_Yr.unique()
Y_values_1 = draft_df.groupby('Draft_Yr').Pk.count()
Y_values_2 = draft_df.groupby('Draft_Yr').WS_per_48.mean()
绘图
代码语言:javascript复制
fig, ax1 = plt.subplots(figsize=(12,9))
title = ('The Number of Players Drafted and Average Career WS/48nfor each Draft (1966-2014)')
plt.title(title,fontsize=20)
plt.grid(axis='y',color='grey',linestyle='--',lw=0.5,alpha=0.5)
plt.tick_params(axis='both',labelsize=14)
plot1 = ax1.plot(X_values,Y_values_1,'b',label='No. of Players Drafted')
ax1.set_ylabel('Number of Players Drafted', fontsize = 18)
ax1.set_ylim(0,240)
for tl in ax1.get_yticklabels():
    tl.set_color('b')    
ax2 = ax1.twinx()
plot2 = ax2.plot(X_values,Y_values_2,'g',label='Avg WS/48')
ax2.set_ylabel('Win Shares Per 48 minutes',fontsize=18)
ax2.set_ylim(0,0.08)
ax2.tick_params(axis='y',labelsize=14)
for tl in ax2.get_yticklabels():
    tl.set_color('g')                    
ax2.set_xlim(1966,2014.15)
lines = plot1   plot2           
ax1.legend(lines,[l.get_label() for l in lines])    
ax1.set_yticks(np.linspace(ax1.get_ybound()[0],ax1.get_ybound()[1],9)) 
ax2.set_yticks(np.linspace(ax2.get_ybound()[0],ax2.get_ybound()[1],9)) 
for ax in [ax1,ax2]:
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)                       
fig.text(0.1,0.02,'The original content: http://savvastjortjoglou.com/nba-draft-part02-visualizing.htmlnPorter: MingYan',fontsize=10)
plt.savefig("Line_chart_4.png")

Line_chart_4.png

0 人点赞