python - Matplotlib 条形图:如何更改轴 x 上的名称
问题描述
我想创建一个条形图,其中包含 2 列数据框的条形图。
from matplotlib import pyplot as plt
import pandas as pd
s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]
df_to_plot = pd.DataFrame(data={"P(S)": p_s,
"P(S|X)": p_s_x,
"S": s})
df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
alpha=0.7,
color=['red', 'green'],
figsize=(8,5))
这个数据框在这里。
我生成的条形图
df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
alpha=0.7,
color=['red', 'green'],
figsize=(8,5));
看起来
我想将 0,1 ,..., 5 替换为 0.1, ..., 0.6 (这是我的列 S),所以我设置了 x。
df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
x='S',
alpha=0.7,
color=['red', 'green'],
figsize=(8,5));
我不知道如何纠正它。我曾经使用参数use_index,xticks,但它们无法工作。
你能看看它并提出建议吗?谢谢!
编辑 感谢@Mr.TI 做了一些更改。
ax = df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
alpha=0.7,
color=['red', 'green'],
figsize=(8,5));
ax.set_xticklabels(df_to_plot['S'])
解决方案
我正在写一个答案,因为由于声誉低,我无法发表评论。给定您的代码,它会使用 matplotlib 3.3.4 版创建预期的输出。 结果图片
from matplotlib import pyplot as plt
import pandas as pd
if __name__ == '__main__':
s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]
df_to_plot = pd.DataFrame(data={"P(S)": p_s,
"P(S|X)": p_s_x,
"S": s})
df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
x='S',
alpha=0.7,
color=['red', 'green'],
figsize=(8,5))
plt.show()
推荐阅读
- r - 使用具有层次聚类的距离矩阵查找聚类数
- javascript - 如何使后退按钮文本正确显示使用 URL 方案打开的应用程序中的最后一个应用程序的名称?
- c# - 尝试通过和迁移共享数据库上下文时出错
- regex - 如何使用引号作为转义序列将值与字符串分开?
- aspnetboilerplate - 管道构建 devops
- python - 我从这段代码返回一个 JSON 响应,我得到 [ ]
- angularjs - Firestore:snapshotChanges 不是函数
- php - 寻找将小时和分钟附加到修改后的 Datetime 对象的更好方法
- jenkins - 使用 Jenkins 触发器执行管道的测试套件运行
- javascript - 如何使用 Javascript 淡出元素