繁体   English   中英

如何使用matplotlib设置x轴顺序为pandas 2.1.2

[英]How to set the x-axis order with pandas using matplotlib 2.1.2

我希望 plot 在 x 轴上从左到右显示一条增加的线。 因此,x 轴需要按以下顺序排列:

JHG C ABEFDIKL

然后这条线将从左到右增加。

df1 = pd.DataFrame({'Col1': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'],
        'Col2': [0, 1, -1, 4, 2, 3, -2 , -3, 5, -5, 6, 7]
        })
df1.sort_values('Col2', inplace=True)
df1.reset_index(drop=True, inplace=True)

df1.index.astype(str) + '_' + df1.iloc[:, 0]

plt.plot(df1.Col1, df1.Col2);

在此处输入图像描述

我什至尝试将索引号(排序后)添加为 x 轴的前缀,但它仍然排序不准确(从 0 到 10 到 11 到 1 等)。

plt.plot(df1.index.astype(str) + '_' + df1.iloc[:, 0], df1.Col2);

在此处输入图像描述

有谁知道如何使用 matpotlib 2.1.2 防止 x 轴按字母顺序排序? 问题是我使用的是 matplotlib 2.1.2,由于公司防火墙问题,我无法更新到更新的版本。

添加一些额外的上下文以防有帮助。

这是一个 function 我正在尝试从 Udemy 课程中编写。 不幸的是,导师并没有回答我的问题。 (我可以为这个提供者提供强烈的负面评论......大声笑)

无论如何,我想使用这个 function - 那么我该如何调整 function 并防止它按字母顺序对 x 轴进行排序?

# Write a funtion that plots by WoE
def plot_by_woe(df_WoE, rotation_of_x_axis_labels=0):
    x = np.array(df_WoE.iloc[:, 0].apply(str))
    y = df_WoE['WoE']
    plt.figure(figsize= (18,6))
    plt.plot(x, y, marker='o', linestyle = '--', color = 'k')
    plt.xlabel(df_WoE.columns[0])
    plt.ylabel('WoE')
    plt.title(str('WoE by ' + df_WoE.columns[0]))
    plt.xticks(rotation = rotation_of_x_axis_labels)

我不确定为什么会这样……但这是我所做的有效的事情。

df = df_temp[['grade','WoE']]
df

# grade WoE
# 0 G   -1.113459
# 1 F   -0.975440
# 2 E   -0.678267
# 3 D   -0.391843
# 4 C   -0.049503
# 5 B   0.358476
# 6 A   1.107830

fig = plt.figure(figsize = (18,6))
ax = fig.add_subplot(111)
ax.plot(np.arange(len(df.grade)), df.WoE, color='k', marker='o', linestyle='dashed')
ax.set_xticks(range(df.grade.count()))
_ = ax.set_xticklabels(df.grade)

在此处输入图像描述

并更新了 function:

# Write a funtion that plots by WoE
def plot_by_woe(df_WoE, rotation_of_x_axis_labels=0):
#     x = np.array(df_WoE.iloc[:, 0].apply(str))
#     y = df_WoE['WoE']
    fig = plt.figure(figsize = (18,6))
    ax = fig.add_subplot(111)
    ax.plot(np.arange(len(df_WoE.iloc[:, 0])), df_WoE.WoE, color='k', marker='o', linestyle='dashed')
    ax.set_xticks(range(df_WoE.iloc[:, 0].count()))
    ax.set_xticklabels(df_WoE.iloc[:, 0])
    plt.xticks(rotation = rotation_of_x_axis_labels)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM