python - 当我尝试创建不连续轴时,为什么我的条形图会变成折线图?

标签 python matplotlib bar-chart data-visualization yaxis

我正在尝试在条形图上创建不连续的 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()

Resulting plots

最佳答案

问题是,您首先绘制条形图,然后使用 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 中的线即可。官方示例

输出

enter image description here

关于python - 当我尝试创建不连续轴时,为什么我的条形图会变成折线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52339645/

相关文章:

python - 在 Python 中从字节字符串中删除前 20 个字节的最快方法是什么?

python - 将 x 的函数作为 x 刻度标签

python - 使用 ginput 时使用 matplotlib.figure 与 pylab 时出错

php - 使用 php 绘制 bargraph-jpgraph

python - 将 pygame 2d 水波纹转换为 pyOpenGL

python - 用它的神奇行为掩盖内置变量?

d3.js - 使用 d3.js 缩放条形图

colors - 使用 chart.js 的条形图的 X 轴多色标签

Python 3 获取子元素(lxml)

python - 如何从Python中的对象数据框列绘制饼图?