最近在学习使用Python画图,想用subplot画两幅箱型图,分别用来表示三组数据在空间滤波前后WRMS值的变化情况。关于Pycharm的安装和配置可以自行百度,直接贴上代码,给出效果图。代码中给出标注以便日后查询。
import pandas as pd #导入pandas
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
#fig,axes = plt.subplots(1,2,figsize=(8,4))
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,sharex=True, figsize=(6, 3))
n_wrms_before_filtering=[]
e_wrms_before_filtering=[]
u_wrms_before_filtering=[]
n_wrms_after_filtering=[]
e_wrms_after_filtering=[]
u_wrms_after_filtering=[]
lines = open("D:\软件安装\SoftwareFile\Pycharm\PycharmProjects\\boxplot\data\wrms_neu1.dat", 'r').readlines()
for i in range(len(lines)):
# split data
fields = lines[i].split(' ')
n_wrms_before_filtering.append(float(fields[0]))
e_wrms_before_filtering.append(float(fields[1]))
u_wrms_before_filtering.append(float(fields[2]))
lines = open("D:\软件安装\SoftwareFile\Pycharm\PycharmProjects\\boxplot\data\wrms_neu2.dat", 'r').readlines()
for i in range(len(lines)):
# split data
fields = lines[i].split(' ')
n_wrms_after_filtering.append(float(fields[0]))
e_wrms_after_filtering.append(float(fields[1]))
u_wrms_after_filtering.append(float(fields[2]))
labels = 'N','E','U' #图例
p1=ax1.boxplot([n_wrms_before_filtering, e_wrms_before_filtering, u_wrms_before_filtering],widths = 0.8,labels = labels,patch_artist = True)
color = ['#515151', '#f14040', '#1a6fdf'] # 有多少box就对应设置多少颜色
for box, c in zip(p1['boxes'], color):
# 箱体边框颜色
box.set(color=c, linewidth=1.5)
# 箱体内部填充颜色
box.set(facecolor=c)
# 这里设置的是各个box的其他属性
for whisker in p1['whiskers']:
whisker.set(color='#180405', linewidth=1.5)
for cap in p1['caps']:
cap.set(color='#180405', linewidth=1.5)
for median in p1['medians']:
median.set(color='#180405', linewidth=1.5)
for flier in p1['fliers']:
flier.set(marker='o', color='y', alpha=0.5)
labels = 'N','E','U' #图例
p2=ax2.boxplot([n_wrms_after_filtering, e_wrms_after_filtering, u_wrms_after_filtering],widths = 0.8,labels = labels,patch_artist = True)
color = ['#515151', '#f14040', '#1a6fdf'] # 有多少box就对应设置多少颜色
for box, c in zip(p2['boxes'], color):
# 箱体边框颜色
box.set(color=c, linewidth=1.5)
# 箱体内部填充颜色
box.set(facecolor=c)
# 这里设置的是各个box的其他属性
for whisker in p2['whiskers']:
whisker.set(color='#180405', linewidth=1.5)
for cap in p2['caps']:
cap.set(color='#180405', linewidth=1.5)
for median in p2['medians']:
median.set(color='#180405', linewidth=1.5)
for flier in p2['fliers']:
flier.set(marker='o', color='y', alpha=0.5)
ax1.set(xlabel='Directions', ylabel='WRMS/mm')
ax2.set(xlabel='Directions', ylabel='WRMS/mm')
ax1.set_title('Before filtering')
ax2.set_title('After filtering')
plt.tight_layout()
#plt.subplots_adjust(left=0.129, bottom=0.11, right=0.9, top=0.88,wspace=0.2, hspace=0.2)
#plt.show()
plt.savefig('D:\软件安装\SoftwareFile\Pycharm\PycharmProjects\\boxplot\\123', dpi=600)
效果图:
本次绘图参考的博客有:
- Matplotlib - 箱线图、箱型图 boxplot () 所有用法详解
- 在一幅图中为箱线图设置不同颜色
- matplotlib官方手册
注:本次绘图中的颜色搭配来自于:学术文章绘图常用颜色搭配(附RGB值)
由于python画图设置颜色的时候用到的为16进制的表示方式,所以我还借鉴了如何把rgb颜色值转换成16进制??所说的,在这里ColorHaxa完成了颜色表达方式的转化。