python - 如何在 Matplotlib 中将子图旋转 45 度?

标签 python matplotlib graph subplot imshow

我正在尝试探索一个子图 2,其形状为旋转 45 度的正方形。

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

data = np.random.rand(10, 10) * 20

# create discrete colormap
cmap = colors.ListedColormap(['red', 'blue','green'])
bounds = [0,5,10,15]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig, ax= plt.subplots(1,2)

ax[0].imshow(data, cmap=cmap, norm=norm)

# draw gridlines
ax[0].grid(which='major', axis='both', linestyle='-', color='k', linewidth=0)
ax[0].set_xticks(np.arange(-.5, 10, 1));
ax[0].set_yticks(np.arange(-.5, 10, 1));


ax[1].imshow(data, cmap=cmap, norm=norm)

# draw gridlines
ax[1].grid(which='major', axis='both', linestyle='-', color='k', linewidth=0)
ax[1].set_xticks(np.arange(-.5, 10, 1));
ax[1].set_yticks(np.arange(-.5, 10, 1));

plt.show()

实际结果是:-

enter image description here

我想将单个图旋转 45 度。像这样的东西:- enter image description here

我正在尝试在 Matplotlib 文档中查找。还是没有得到。有什么帮助吗?

请注意,这不是重复的

Is there a way to rotate a matplotlib plot by 45 degrees?

上述 URL 用于绘图。解决办法是旋转IMAGE。然而,这与次要情节有关。我想旋转绘图而不是整个图像。

最佳答案

基于此link和有关 floating_axes 的文档,你可以尝试这样的事情:

from mpl_toolkits.axisartist.grid_finder import DictFormatter
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib import colors
import numpy as np

def setup_axes1(fig, rect, angle):
    tr = Affine2D().scale(2, 2).rotate_deg(angle)

    #We create dictionarys to keep the xticks and yticks after the rotation
    dictio={i:str(val) for i,val in enumerate(np.arange(-.5, 10, 1).tolist())}
    reversedictio={i:dictio[val] for i,val in enumerate(list(reversed(sorted(dictio.keys()))))}
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr, extremes=(-0.5, 9.5,-0.5, 9.5), tick_formatter1= DictFormatter(dictio),
        tick_formatter2=DictFormatter(reversedictio))

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)


    fig.add_subplot(ax1) 
    aux_ax = ax1.get_aux_axes(tr)
    grid_helper.grid_finder.grid_locator1._nbins = 10    #Number of rows
    grid_helper.grid_finder.grid_locator2._nbins = 10    #Number of columns
    return aux_ax

fig1, axes=plt.subplots(2,figsize=(20,20))
plt.rcParams.update({'font.size': 27})

#We erase the first previous axes
fig1.delaxes(axes[0])
fig1.delaxes(axes[1])

data = np.random.rand(10, 10) * 20

#We create the floating_axes
ax0 = setup_axes1(fig1, 121,-45)
ax1 = setup_axes1(fig1, 122,-45)
# create discrete colormap
cmap = colors.ListedColormap(['red', 'blue','green'])
bounds = [0,5,10,15]
norm = colors.BoundaryNorm(bounds, cmap.N)

ax0.imshow(data, cmap=cmap, norm=norm,interpolation="nearest")
# draw gridlines
ax0.grid(which='major', axis='both', linestyle='-', color='k', linewidth=0)

ax1.imshow(data, cmap=cmap, norm=norm,interpolation="nearest")  
# draw gridlines
ax1.grid(which='major', axis='both', linestyle='-', color='k', linewidth=0)    

plt.show()

输出:

enter image description here

或者,作为另一种选择,我找到了一种“棘手”的方法来做到这一点,它是关于捕获缓冲区中的数字,将它们旋转-45度,然后将它们合并成一个图像,因为你有相同的两张图片,您可以尝试这样的操作:

import matplotlib
import io
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np



##PLOTING THE FIGURE##

data = np.random.rand(10, 10) * 20

# create discrete colormap
cmap = colors.ListedColormap(['red', 'blue','green'])
bounds = [0,5,10,15]
norm = colors.BoundaryNorm(bounds, cmap.N)

#We change style values to get the image with better quality

plt.rcParams.update({'font.size': 46})
plt.figure(figsize=(20,20))
plt.imshow(data, cmap=cmap, norm=norm)

# draw gridlines
plt.grid(which='major', axis='both', linestyle='-', color='k', linewidth=0)
plt.gca().set_xticks(np.arange(-.5, 10, 1));
plt.gca().set_yticks(np.arange(-.5, 10, 1));


##SAVING THE FIGURE INTO AN IMAGE##

#We save the current figure as a Image
buf = io.BytesIO()
plt.savefig(buf, format='png',bbox_inches='tight')
buf.seek(0)
im = Image.open(buf)  #We open the current image saved in the buffer

#We rotate the image and fill the background with white
img_01=im.rotate(-45, Image.NEAREST, expand = 1, fillcolor = (255,255,255))


buf.close()


##MERGING THE TWO FIGURES##

new_im = Image.new('RGB', (2*img_01.size[0]+20,img_01.size[1]), 'white')
mouse_mask = img_01.convert('RGBA')
new_im.paste(img_01, (0,0))
new_im.paste(img_01, (img_01.size[0]+8,0))
new_im.save("merged_images.png", 'PNG') #Important(just to clarify): save the image, since the buffer is renewed every time you run the script
new_im.show()

输出: enter image description here

我通过这些链接帮助自己:

关于python - 如何在 Matplotlib 中将子图旋转 45 度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62357483/

相关文章:

python - 两个文件的区别

python - 将相同的 x 轴标签传递给 matplotlib 条形图的子图

python - Matplotlib:导入错误没有名为_path的模块

algorithm - 最大权重二分匹配

csv - ArangoDB 将 csv 导入边缘(图表)

python - CX_Freeze exe 引用旧的 pyc 文件?

python - TensorFlow:了解 tf.summary.scalar 中的 `collections` 参数

python - 如何通过 pandas 中的 groupby 输出来填充 na?

python - 在用 numpy 绘图时使用修改后的 arctan2 的错误

algorithm - 弱连通平衡有向图