【问题标题】:How to rotate a Subplot by 45 degree in Matplotlib?如何在 Matplotlib 中将子图旋转 45 度?
【发布时间】:2020-10-03 01:12:51
【问题描述】:

我正在尝试探索一个旋转 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()

实际结果是:-

我想将单个图旋转 45 度。类似的东西:-

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

请注意这不是重复的

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

提到的 URL 是一个情节。解决方案是旋转图像。然而,这与子图有关。我想旋转 PLOT 而不是整个图像。

【问题讨论】:

标签: python matplotlib graph subplot imshow


【解决方案1】:

基于此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()

输出:

或者,作为另一种选择,我找到了一种“棘手”的方法,它是关于捕捉缓冲区中的数字,将它们旋转 -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()

输出:

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

【讨论】:

  • 你真的需要floating_axes
  • 我可以使用它,就像我在回答中所做的那样,但也有其他方法,不过还是感谢您的建议!
  • 好吧,当您将渲染良好的文本保存到图像中然后旋转图像时,文本看起来会很糟糕。参见例如wikipedia 关于使文本看起来不错的所有工作。您的解决方法“有效”,但当存在更好的解决方案时,这是一个非常糟糕的主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多