首页 > 解决方案 > 更改组合 sns python 图中的项目顺序

问题描述

我需要一个具有三个不同轴的绘图图。到目前为止,我改编了我在网上找到的一个脚本。不幸的是,我注意到我的数据没有正确排序。起初,我按名为“a”的列对数据框进行排序,但在最终图中,似乎只有这一列已排序。我想订购所有这些。当我在排序后打印数据框时,一切似乎都很好。我将非常感谢任何帮助。 这是我根据“a”列对其进行排序后的数据框 ,这是最终图表,其中仅对流域区域进行了排序,但流域名称、流域平均高程和流域平均坡度未正确排序

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
from matplotlib.ticker import PercentFormatter

data1 = 'path to my .xlsx file'
df = pd.read_excel(data1, 'catchments_basic')# loading data 
df_sorted = df.sort_values(by=['a'], ascending=False)

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

sns.set(style="white", rc={"lines.linewidth": 3})
fig, ax = plt.subplots(figsize=(15,10))
fig.subplots_adjust(right=0.75)

ax1 = ax.twinx()
ax2 = ax.twinx()

# Offset the right spine of par2.  The ticks and label have already been
# placed on the right by twinx above.
ax2.spines["right"].set_position(("axes", 1.1))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible.  First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(ax2)
# Second, show the right spine.
ax2.spines["right"].set_visible(True)


host = sns.barplot(x=df_sorted['Catchment'],
            y=df_sorted["a"],
            color='#004488',
            label="area",
            ax=ax)
par1 = sns.lineplot(x=df_sorted['Catchment'], 
             y=df_sorted["b"],
             color='r',
             marker="o",
             label="mean elevation",
             ax=ax1)
par2 = sns.lineplot(x=df_sorted['Catchment'], 
             y=df_sorted["c"],
             color='g',
             marker="o",
             label="mean slope",
             ax=ax2)


host.set_xlim(-1, 20)
host.set_ylim(0, 1000)
par1.set_ylim(0, 1000)
par2.set_ylim(0, 100)

host.set_xlabel("river catchment")
host.set_ylabel("area [$km^2$]")
par1.set_ylabel("mean elevation [m n. m.]")
par2.set_ylabel("mean slope [%]")

host.yaxis.label.set_color(color='#004488')
par1.yaxis.label.set_color(color='r')
par2.yaxis.label.set_color(color='g')


tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors='#004488', **tkw)
host.tick_params(axis='x', colors='black', **tkw)
par1.tick_params(axis='y', colors='r', **tkw)
par2.tick_params(axis='y', colors='g', **tkw)
host.tick_params(axis='povodie', **tkw)

ax2.yaxis.set_major_formatter(PercentFormatter(decimals=0))
for tick in host.get_xticklabels():   
    tick.set_rotation(45)

host.set_title('Area, mean altitude and mean slope in selected river catchments', family='Arial', size=12, weight='bold')

host.grid(linestyle="dotted", color='black')
host.legend(loc='upper left')
par1.legend(loc='upper center')
par2.legend(loc='upper right')


save_results_to = 'path where I want to save figure 
plt.tight_layout(pad=2) 
plt.savefig(save_results_to + 'basic_characteristics_bar_line_combination.png', dpi = 300)
plt.show()

print ('done')

标签: pythongraphline

解决方案


您应该将 sns.lineplot 中的排序参数更改为 False


推荐阅读