
我有2个子图-1个散点和一个条形图,我想要一个共享的x轴。散点图有一个颜色条。共享似乎与此不同,因为两个图的轴不重合。我的代码:
fig, (ax, ax2) = plt.subplots(2,1, gridspec_kw = {'height_ratios':[13,2]},figsize=(15,12), sharex=True)
df_plotdata.plot(kind='scatter', ax=ax, x='index_cancer', y='index_g', s=df_plotdata['freq1']*50, c=df_plotdata['freq2'], cmap=cmap)
df2.plot(ax=ax2, x='index_cancer', y='freq', kind = 'bar')发布于 2017-10-12 19:58:09
Sharex表示轴限制相同,并且轴是同步的。这并不意味着它们相互重叠。这完全取决于您如何创建颜色栏。
像matplotlib中的任何statndard颜色栏一样,pandas散点图创建的颜色栏是通过删除与其相关的轴的部分空间来创建的。因此,这个轴比网格中的其他轴小。
您拥有的选项包括:
使用与散点图轴数相同的量对网格的其他轴线进行
这可以通过使用第一个轴的位置并使用ax.get_position()和ax.set_postion()相应地设置第二个轴的位置来完成
将高度作为plt导入熊猫作为pd导入numpy作为np导入itertools as it xy = matplotlib.pyplot ( it.product( range(10),range(10) )) df = pd.DataFrame( xy,columns='x','y‘)df’matplotlib.pyplot‘= np.random.random( 100 ) kw = {'height_ratios':13,2} fig,(ax,ax2) = plt.subplots(2,1,gridspec_kw=kw,sharex=True) df.plot(kind=’it.product‘,x='x',y='y',c='score',s=100,cmap="PuRd",ax=ax,colorbar=True) df.groupby("x").mean().plot(kind = 'bar',y='score',ax=ax2,legend=False) ax2.legend(bbox_to_anchor=(1.03,0),loc=3) pos = ax.get_position() pos2 = ax2.get_position() ax2.set_position(pos.x0,pos2.y0,pos.width,pos2.height) plt.show()

在这种情况下,您可以创建一个4 x 4的网格,并将颜色条添加到该网格的右上角。这需要将散点图提供给fig.colorbar()并指定色条所在的轴,
fig.colorbar(ax.collections,cax=cax)然后删除不需要的右下轴(ax.axis("off"))。如果需要,您仍然可以通过ax2.get_shared_x_axes().join(ax, ax2)共享这些轴。
将高度作为plt导入熊猫作为pd导入numpy作为np导入itertools as it xy = list( it.product(范围(10),范围(10))) df = pd.DataFrame( xy,列=‘x’,'y‘)df’matplotlib.pyplot‘= np.random.random( 100 ) kw = {'height_ratios':13,2,"width_ratios":95,5} fig,((ax,cax),(ax2,aux)) = plt.subplots(2,2,gridspec_kw=kw) df.plot(kind=’散点‘,x='x',y='y',c='score',s=80,cmap="PuRd",ax=ax,colorbar=False) df.groupby("x").mean().plot(kind = 'bar',y='score',ax=ax2,legend=False) fig.colorbar(ax.collections,cax=cax,label="score") aux.axis("off") ax2.legend(bbox_to_anchor=(1.03,0),loc=3) ax2.get_shared_x_axes().join(ax,)(“x”,labelbottom=0) ax.set_xlabel("") plt.show()

发布于 2019-09-25 22:10:45
根据ImportanceOfBeingErnest的回答,以下两个函数将对齐轴:
def align_axis_x(ax, ax_target):
"""Make x-axis of `ax` aligned with `ax_target` in figure"""
posn_old, posn_target = ax.get_position(), ax_target.get_position()
ax.set_position([posn_target.x0, posn_old.y0, posn_target.width, posn_old.height])
def align_axis_y(ax, ax_target):
"""Make y-axis of `ax` aligned with `ax_target` in figure"""
posn_old, posn_target = ax.get_position(), ax_target.get_position()
ax.set_position([posn_old.x0, posn_target.y0, posn_old.width, posn_target.height])发布于 2021-12-06 21:41:43
使用Matplotlib工具包(包含在Matplotlib中)
我想在当前答案的基础上添加一个替代方案,即使用Matplotlib工具包中的函数make_axes_locatable。默认情况下,这会优化空间的使用。如果你有一个复杂的子图配置,其中有几个这种类型的子图,这会产生很大的不同,例如,使用gridspec。
使用示例
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools as it
from mpl_toolkits.axes_grid1 import make_axes_locatable
# create some data
xy = list(it.product(range(16), range(16)))
df = pd.DataFrame(xy, columns=["x", "y"])
df["bubles"] = np.random.random(256)
# create figure and main axis
fig = plt.figure(figsize=(10,6))
ax = plt.gca()
# create a divider from make_axes_locatable
divider = make_axes_locatable(ax)
# append a new axis on the bottom whose size is 15% of the size of the main ax
bax = divider.append_axes("bottom", size="15%", pad=.05)
# append axis on the right for colourbar (size = 5%)
cax = divider.append_axes("right", size="5%", pad=.05)
cm = "plasma" # defining colourmap
sm = plt.cm.ScalarMappable(cmap=cm)
# plotting on main axis
p1 = df.plot(kind='scatter', x='x', y='y', c='bubles', s=df["bubles"]*200, cmap=cm,
ax=ax, colorbar=False)
# attaching colourbar to the axis at the right
plt.colorbar(sm, cax=cax)
# plotting on the adjascent axis (bottom)
p2 = df.groupby("x").mean().plot(kind = 'bar', y='bubles',ax=bax, legend=False)
# synchronizing plots on the x-axis
p2.sharex(p1)
# inserting some legend
bax.legend(bbox_to_anchor=(1.03,0),loc=3)
plt.show()上面的代码产生了如下图:

有关sharex对两个x轴同步的影响,请参见下面的GIF:

https://stackoverflow.com/questions/46694889
复制相似问题