我正在尝试在条形图上创建不连续的 y 轴。我可以根据需要打破轴,但生成的图表看起来像我的数据的线图,而不是我原来的条形图。在附图中,我希望顶部轴上的条形图出现在底部图的轴框架上。
谢谢。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame(np.c_[PURO, MYC, HRAS, CYCD, AURKB], index=Phenotype)
df.plot.bar()
plt.xlabel('Phenotype (# of poles, total # of centrioles)')
plt.ylabel('# of cells')
fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, sharey=False)
ax.plot(df)
ax2.plot(df)
ax.set_ylim(40,100)
ax2.set_ylim(0,20)
ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.xaxis.tick_bottom()
plt.show()
最佳答案
问题是,您首先绘制条形图,然后使用 ax.plot() 和 ax2.plot() 绘制两倍的 DataFrame,后者仅绘制连接线。
解决方案:删除以下行
df.plot.bar()
并将 ax.plot(df)
和 ax2.plot(df)
替换为
df.plot.bar(ax=ax)
df.plot.bar(ax=ax2)
下面是使用虚拟 DataFrame 为您提供的最小工作答案(不包括导入)。同样的情况也适用于您的情况。
fig = plt.figure(figsize=(8, 6))
df = pd.DataFrame({'count': {0: 88, 1: 67, 2: 10, 3: 16, 4: 18}}).reset_index()
fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, sharey=False)
df.plot.bar(x='index', y='count', legend=False, ax=ax)
df.plot.bar(x='index', y='count', legend=False, ax=ax2)
ax.set_ylim(50,100)
ax2.set_ylim(0,20)
ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.xaxis.tick_bottom()
您可以添加对角线/小线来突出显示虚线,只需复制 this 中的线即可。官方示例
输出
关于python - 当我尝试创建不连续轴时,为什么我的条形图会变成折线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52339645/