Python中如何调整sns relplot的图层顺序避免折线遮挡
是否可以调整sns relplot生成的图表中不同曲线的图层上下顺序?
现有包含三条折线的图表,其中绿色的outside_temperature曲线遮挡了另外两条曲线temp_20和temp_60。
期望的图层顺序为:temp_60位于最上层,temp_20位于中间层,outside_temperature位于最底层。
生成图表的原始代码
def create_lineplot(sensor1, sensor2): months = mdates.MonthLocator() # 每月生成一个主刻度 years_fmt = mdates.DateFormatter('%Y-%m') # 日期显示格式为年-月 # 筛选2020年的相关列数据 sensor1_copy = sensor1[['dev_id', 'temp_20', 'temp_60', 'datetime']].copy() sensor1_copy["datetime"] = pd.to_datetime(sensor1_copy["datetime"]) sens1 = sensor1_copy[sensor1_copy['datetime'].dt.year == 2020] # 筛选2020年的相关列数据 sensor2_copy = sensor2[['dev_id', 'outside_temperature', 'datetime']].copy() sensor2_copy["datetime"] = pd.to_datetime(sensor2_copy["datetime"]) sens2 = sensor2_copy[sensor2_copy['datetime'].dt.year == 2020] cdf = pd.concat([sens1, sens2]) mdf = pd.melt(cdf, id_vars=['datetime', 'dev_id'], var_name=['Temperature']) mdf.rename(columns={"value": "Temperature in Celsius C", "datetime": "Datetime"}, inplace = True) print(mdf) g = sns.relplot(data=mdf, x='Datetime', y='Temperature in Celsius C', kind='line', hue='Temperature', height=5, aspect=3) g._legend.remove() axes = g.axes.flat[0] axes.xaxis.set_major_locator(months) axes.xaxis.set_major_formatter(years_fmt) axes.xaxis.set_minor_locator(months) plt.xticks(rotation='vertical') plt.tight_layout() plt.legend(loc='upper right') plt.savefig('lineplot.png') plt.show()
mdf数据示例(print(mdf)输出)
Datetime dev_id Temperature Temperature in Celsius C 2020-02-04 16:32:21 sensor1 temp_20 4.52 2020-02-04 17:32:25 sensor1 temp_20 4.48 ... ... ... ... 2020-02-13 02:45:45 sensor1 temp_60 2.34 2020-02-13 03:45:49 sensor1 temp_60 2.32 ... ... ... ... 2020-03-13 20:39:54 sensor2 outside_temperature 6.00 2020-03-13 20:49:53 sensor2 outside_temperature 6.50
调整方法
sns的relplot支持通过hue_order参数控制不同hue分类的绘制顺序,参数列表中的分类会按从左到右的顺序依次绘制,越靠后的分类图层越靠上,刚好匹配需求,修改后的代码如下:
g = sns.relplot(data=mdf, x='Datetime', y='Temperature in Celsius C', kind='line', hue='Temperature', hue_order=['outside_temperature', 'temp_20', 'temp_60'], height=5, aspect=3)

未添加outside_temperature曲线时,temp_20和temp_60的显示效果如下:
内容的提问来源于stack exchange,提问作者Buster3650
相关产品推荐
相关产品推荐

