如何使用matplotlib 2.1.2设置Pandas的xaxis顺序

2024-04-28 21:35:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让这个图在x轴上从左到右显示, 渐增的线。因此,x轴的顺序如下:

J H G C A B E F D I K L

然后直线将从左向右增加

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);

enter image description here

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

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

enter image description here

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

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

这是一个函数,我正试图从我的课程中编写。不幸的是,老师没有回答我的问题。(我可以为这个提供者提供一个强有力的负面评论…哈哈)

在任何情况下,我都想使用这个函数-那么我如何调整这个函数并防止它按字母顺序排列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)

Tags: 函数truedfindexby排序plot顺序
1条回答
网友
1楼 · 发布于 2024-04-28 21:35:34

我不太清楚为什么这样做有效……但我做了一些有用的事情

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)

enter image description here

和更新的功能:

# 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)

相关问题 更多 >