简体   繁体   English

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

[英]How to rotate a Subplot by 45 degree in Matplotlib?

I am trying to explore a subplot 2 plots with square in shape rotated by 45 degree.我正在尝试探索一个旋转 45 度的正方形的子图 2 地块。

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

Actual Result is:-实际结果是:-

在此处输入图像描述

I want to rotate individual plot by 45 degree.我想将单个 plot 旋转 45 度。 Something like:-就像是:- 在此处输入图像描述

I am trying to find in Matplotlib Documentation.我试图在 Matplotlib 文档中找到。 Still not getting.仍然没有得到。 Any help?有什么帮助吗?

Please note this is NOT DUPLICATE OF请注意,这不是重复的

Is there a way to rotate a matplotlib plot by 45 degrees? 有没有办法将 matplotlib plot 旋转 45 度?

The mentioned URL is for a plot.提到的 URL 用于 plot。 and the solution is to rotate IMAGE.解决方案是旋转图像。 However this is pertaining to Subplot.然而,这与子图有关。 I want to rotate PLOT not image as whole.我想旋转 PLOT 而不是整个图像。

Based on this link and documentation about floating_axes , you can try something like this:基于此链接和有关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()

Output: Output:

在此处输入图像描述

Or, as an other alternative, I found a "tricky" way to do it, and it's about catching the figures in the buffer, rotate them -45 degrees, and then merge them into a single image, and since you have the same two images, you can try something like this:或者,作为另一种选择,我找到了一种“棘手”的方法,它是关于捕获缓冲区中的数字,将它们旋转 -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()

Output: Output: 在此处输入图像描述

I helped myself with these links:我通过这些链接帮助自己:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM