【问题标题】:how to customize x-axis in matplotlib when plotting绘图时如何在matplotlib中自定义x轴
【发布时间】:2018-12-01 00:51:24
【问题描述】:

我有一个条形图,x 轴是 (1,2,3...12)。 所以我的条形图是这样的:

我该如何改变:

1---> -6month 
2---> -1 year
3--->-1.5 year
.
.
.

在展示的时候?

我要绘制的代码是:

dffinal = df[['6month','final-formula','Question Text','numPatients6month']].drop_duplicates().sort_values(['6month'])

df = dffinal.drop('numPatients6month', 1).groupby(['6month','Question Text']).sum().unstack('Question Text')

df.columns = df.columns.droplevel()
ax=df.plot(kind='bar', stacked=True)
import matplotlib.pyplot as plt
ax2 = ax.twinx()
plt.xticks(fontsize=8, rotation=45)
#ax2.spines['right'].set_position(('axes', 1.0))
dffinal.plot(ax=ax2,x='6month', y='numPatients6month',visible=False)
plt.title('Cognitive Impairement-Stack bar')
plt.show()

我有两个 df,因为我有两个 y 轴。

我尝试使用替换:

   dffinal['6month'].replace(1, '-6 month',inplace=True)
dffinal['6month'].replace(2, '-1 year',inplace=True)

但它只是没有工作。

谢谢:)

【问题讨论】:

  • 抱歉,您的代码和您显示的绘图之间几乎没有共同点 :-) 您的意思是仅更改显示某些文本的 x 刻度而不是 1、...、12?如果是这样,您只需要编写一个类似plt.xticks(range(1,13), ['-6month','-1 year',...], fontsize=8, rotation=90) 的命令,而不是您当前拥有的plt.xticks。您的问题标题说 y 轴,但在这种情况下,y 轴对文本/分类变量没有多大意义......
  • @MarcoSpinaci 感谢您的回复我刚刚编辑了标题。我的脑子里充满了上一个问题,这就是为什么你会看到一些冲突。我不知道我可以在 x.ticks 中添加它现在我正在尝试你的代码,然后我会更新
  • 关于情节和代码之间的冲突,你是对的,我绘制了一个我有但不想运行有问题的代码的例子
  • @MarcoSpinaci 它工作得很好,除了它应该是 range(0,12) 。请添加您的答案,以便我可以选择它作为所需的答案:)

标签: pandas matplotlib bar-chart visualization data-analysis


【解决方案1】:

命令plt.xticks 应该会处理它。根据 x 轴的计数是从 0(默认情况下)还是从 1(如您的情节暗示)开始,您可以尝试:

# If x starts from 0
plt.xticks(range(12), ['-6month','-1 year',...], fontsize=8, rotation=90)

# If x starts from 1
plt.xticks(range(1,13), ['-6month','-1 year',...], fontsize=8, rotation=90)

在这两种情况下,将 ['-6month','-1 year',...] 替换为您想要的标签的 12 个元素列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2017-01-01
    • 2020-06-09
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多