Python-双Y轴图表,零对齐

时间:2018-06-26 03:45:34

标签: python pandas matplotlib

我正在尝试创建带有两个x轴的水平条形图。这两个轴在比例上有很大不同,一组从-5到15(正值和负值),另一组从100到500(所有正值)。

当我绘制此图形时,我想对齐2个轴,以便零显示在同一位置,并且只有负值位于该坐标的左侧。当前,所有正值的集合都从最左端开始,正负值的集合都从整个图的中间开始。

我找到了align_yaxis示例,但是我正在努力对齐x轴。 Matplotlib bar charts: Aligning two different y axes to zero

这里是我正在使用简单测试数据进行处理的示例。有什么想法/建议吗?谢谢

import pandas as pd
import matplotlib.pyplot as plt

d = {'col1':['Test 1','Test 2','Test 3','Test 4'],'col 2':[1.4,-3,1.3,5],'Col3':[900,750,878,920]}
df = pd.DataFrame(data=d)

fig = plt.figure()  # Create matplotlib figure

ax = fig.add_subplot(111)  # Create matplotlib axes
ax2 = ax.twiny()  # Create another axes that shares the same y-axis as ax.

width = 0.4

df['col 2'].plot(kind='barh', color='darkblue', ax=ax, width=width, position=1,fontsize =4, figsize=(3.0, 5.0))
df['Col3'].plot(kind='barh', color='orange', ax=ax2, width=width, position=0, fontsize =4, figsize=(3.0, 5.0))

ax.set_yticklabels(df.col1)
ax.set_xlabel('Positive and Neg',color='darkblue')
ax2.set_xlabel('Positive Only',color='orange')

ax.invert_yaxis()
plt.show()

1 个答案:

答案 0 :(得分:0)

我遵循了问题的链接,最终得到了以下答案:https://stackoverflow.com/a/10482477/5907969

答案具有对齐y轴的功能,我已经对其进行了如下修改以对齐x轴:

def align_xaxis(ax1, v1, ax2, v2):
    """adjust ax2 xlimit so that v2 in ax2 is aligned to v1 in ax1"""
    x1, _ = ax1.transData.transform((v1, 0))
    x2, _ = ax2.transData.transform((v2, 0))
    inv = ax2.transData.inverted()
    dx, _ = inv.transform((0, 0)) - inv.transform((x1-x2, 0))
    minx, maxx = ax2.get_xlim()
    ax2.set_xlim(minx+dx, maxx+dx)

然后在代码中使用它,如下所示:

import pandas as pd
import matplotlib.pyplot as plt

d = {'col1':['Test 1','Test 2','Test 3','Test 4'],'col 2' [1.4,-3,1.3,5],'Col3':[900,750,878,920]}
df = pd.DataFrame(data=d)

fig = plt.figure()  # Create matplotlib figure

ax = fig.add_subplot(111)  # Create matplotlib axes
ax2 = ax.twiny()  # Create another axes that shares the same y-axis as ax.

width = 0.4

df['col 2'].plot(kind='barh', color='darkblue', ax=ax, width=width, position=1,fontsize =4, figsize=(3.0, 5.0))
df['Col3'].plot(kind='barh', color='orange', ax=ax2, width=width, position=0, fontsize =4, figsize=(3.0, 5.0))

ax.set_yticklabels(df.col1)
ax.set_xlabel('Positive and Neg',color='darkblue')
ax2.set_xlabel('Positive Only',color='orange')

align_xaxis(ax,0,ax2,0)
ax.invert_yaxis()
plt.show()

这将为您提供所需的内容 enter image description here