matplotlib sharex与colorbar不起作用 [英] matplotlib sharex with colorbar not working

查看:207
本文介绍了matplotlib sharex与colorbar不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个子图-1个散点图和一个条形图,我想要一个共享的x轴.散点图有一个色条. sharex似乎与此不兼容,因为两个图的轴不重合. 我的代码:

I have 2 subplots- 1 scatter and one bar for which I would like a shared x axis. The scatter plot has a color bar. The sharex doesn't seem to work with this as the axis for the two plots do not coincide. My code:

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')

推荐答案

Sharex表示轴限制相同,并且轴已同步.这并不意味着它们位于彼此之上.这完全取决于您如何创建颜色栏.

Sharex means that the axes limits are the same and that the axes are synchronized. It doesn't mean that they lie on top of each other. It all depends on how you create the colorbar.

pandas scatterplot创建的颜色条与matplotlib中的任何标准色条一样,是通过占用与其相关的轴的部分空间来创建的.因此,此轴小于网格中的其他轴.

The colorbar created by pandas scatterplot is, just like any statndard colorbar in matplotlib, created by taking away part of the space for the axes that it relates to. Hence this axes is smaller than other axes from the grid.

您提供的选项包括:

  • 将网格的其他轴与散点图轴的收缩量相同.
    这可以通过使用第一轴的位置并相应地使用ax.get_position()ax.set_postion()

  • Shrinking the other axes of the grid by the same amount than the scatterplot axes.
    This can be done by using the position of the first axes and set the position of the second axes accordingly, using ax.get_position() and ax.set_postion()

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools as it

xy = list( it.product( range(10), range(10) ) )
df = pd.DataFrame( xy, columns=['x','y'] )
df['score'] = np.random.random( 100 )

kw = {'height_ratios':[13,2]}
fig, (ax,ax2) = plt.subplots(2,1,  gridspec_kw=kw, sharex=True)

df.plot(kind='scatter', 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()并为色条指定一个驻留轴,

  • Create a grid including an axes for the colorbar.
    In this case you can create a 4 by 4 grid and add the colorbar to the upper right axes of it. This requires to supply the scatter plot to fig.colorbar() and specify an axes for the colorbar to live in,

fig.colorbar(ax.collections[0], cax=cax)       

然后删除不需要的右下轴(ax.axis("off")).如果需要,您仍然可以通过ax2.get_shared_x_axes().join(ax, ax2)共享轴.

Then remove the lower right axes, which is not needed (ax.axis("off")). You may still share the axes, if that is needed, via ax2.get_shared_x_axes().join(ax, ax2).

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools as it


xy = list( it.product( range(10), range(10) ) )
df = pd.DataFrame( xy, columns=['x','y'] )
df['score'] = 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='scatter', 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[0], cax=cax, label="score")
aux.axis("off")
ax2.legend(bbox_to_anchor=(1.03,0),loc=3)
ax2.get_shared_x_axes().join(ax, ax2)
ax.tick_params(axis="x", labelbottom=0)
ax.set_xlabel("")

plt.show()

这篇关于matplotlib sharex与colorbar不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆