我试图绘制一个成本(卢比单位)和装机容量(兆瓦单位)的方框图,其中xaxis
作为可再生能源的份额(单位百分比)
也就是说,每个x记号与两个箱线图关联,一个是成本,一个是装机容量。我有3个xtick值(20%, 40%, 60%)
我尝试了this answer,但我得到了附在底部的错误
我需要每个xtick
两个箱线图
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
plt.rcParams["font.family"] = "Times New Roman"
plt.style.use('seaborn-ticks')
plt.grid(color='w', linestyle='solid')
data1 = pd.read_csv('RES_cap.csv')
df=pd.DataFrame(data1, columns=['per','cap','cost'])
cost= df['cost']
cap=df['cap']
per_res=df['per']
fig, ax1 = plt.subplots()
xticklabels = 3
ax1.set_xlabel('Percentage of RES integration')
ax1.set_ylabel('Production Capacity (MW)')
res1 = ax1.boxplot(cost, widths=0.4,patch_artist=True)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(res1[element])
for patch in res1['boxes']:
patch.set_facecolor('tab:blue')
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('Costs', color='tab:orange')
res2 = ax2.boxplot(cap, widths=0.4,patch_artist=True)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(res2[element], color='k')
for patch in res2['boxes']:
patch.set_facecolor('tab:orange')
ax1.set_xticklabels(['20%','40%','60%'])
fig.tight_layout()
plt.show()
样本数据: data attached
通过测试您的代码并将其与answer by Thomas Kühn in the linked question进行比较,我发现了几个突出的方面:
x
参数输入的数据是一维形状,而不是二维形状。输入一个变量,得到一个框,而不是实际需要的三个框李>positions
参数,这会导致两个箱线图的框重叠李>res1
上的第一个for
循环中,plt.setp
中的color
参数丢失李>我提供了以下基于this answer by ImportanceOfBeingErnest的解决方案。它解决了正确塑造数据的问题,并利用字典定义绘图中多个对象共享的许多参数。这样可以更容易地根据您的喜好调整格式,并使代码更简洁,因为它避免了使用
for
循环(在boxplot元素和res
对象上)以及在共享相同参数的函数中重复参数Matplotlib文档:boxplot demo、boxplot function parameters、marker symbols for fliers、label text formatting parameters
考虑到这是一个相当大的努力来建立这个,如果我是为自己这样做,我会去并排子地块,而不是创建孪生轴。在seaborn中,使用^{} 函数可以很容易地完成这项工作,该函数会自动处理许多格式。由于每个变量只有三个类别,因此使用不同颜色对每个百分比类别并排比较箱线图相对容易,如基于相同数据的本例所示:
相关问题 更多 >
编程相关推荐