【发布时间】:2021-11-23 18:32:12
【问题描述】:
我希望图表在 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);
我什至尝试将索引号(排序后)添加为 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,由于公司防火墙问题,我无法更新到更新的版本。
添加一些额外的上下文以防万一。
这是我尝试从 Udemy 课程中编写的函数。不幸的是,导师没有回答我的问题。 (我可以给这个提供者一个强烈的负面评价......哈哈)
无论如何,我都想使用这个功能——那么我该如何调整这个功能并防止它按字母顺序对 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)
【问题讨论】:
-
您希望得到什么订单?编辑:抱歉没有阅读您的评论 - 只需在 Col2 上对您的数据框进行排序
-
这不适用于 matplotlib 2.1.2。 Matplotlib 自动按字母顺序对 x 轴进行排序,这就是我要避免的。
-
你对
df1的排序如何?在 matplotlib 2.2.5 中,这有效:df1 = df1.sort_values('Col2'); plt.plot(df1.Col1, df1.Col2) -
这不起作用@tdy3,但谢谢。我稍微加强了这个问题,以说明它如何不适用于 2.1.2。
标签: python pandas matplotlib plot x-axis