[英]Is there a way to rotate a matplotlib plot by 45 degrees?
我正在尋找一種方法將matplotlib-pyplot(Python庫)中生成的繪圖旋轉45度(例如,如果不是方形,你會有鑽石形狀),任何人都知道是否可以這樣做?
我能想到的一種方法是對所有數據使用旋轉濾鏡,使其顯示為旋轉,但繪圖本身仍將處於原始方向。
我希望能夠使用matplotlib交互功能,因此保存為圖像然后旋轉將無法正常工作。
此外,我想使用pyplot函數繪制繪圖,因此使用不同的庫進行繪圖並不是一個理想的解決方案。
好的,目前我找到的唯一部分解決方案是對繪圖應用旋轉。 這允許使用matplotlib / pyplot提供的交互式界面。
對於像plot()和scatter()這樣的點圖,這是微不足道的,但我對旋轉imshow()特別感興趣。 此鏈接討論了可能已用於此任務的transform關鍵字,但它顯然無法正常工作。
幸運的是,我找到了使用pcolormesh()的解決方法。 pcolormesh()繪制四邊形網格,並允許您指定角坐標。 因此,答案是將相關變換應用於角坐標。 但請注意,pcolormesh()的工作方式與imshow略有不同 - 它會將您的矩陣翻轉。
我沒有在網絡上的任何地方看到這個解決方案,所以這里有一些代碼為pcolormesh()/ imshow()旋轉了45度:
import matplotlib.pyplot as plt
import numpy as np
def pcolormesh_45deg(C):
n = C.shape[0]
# create rotation/scaling matrix
t = np.array([[1,0.5],[-1,0.5]])
# create coordinate matrix and transform it
A = np.dot(np.array([(i[1],i[0]) for i in itertools.product(range(n,-1,-1),range(0,n+1,1))]),t)
# plot
plt.pcolormesh(A[:,1].reshape(n+1,n+1),A[:,0].reshape(n+1,n+1),np.flipud(C))
基於Bitwise anwer,您可以使用以下功能:
def pcolormesh_45deg(C, ax=None, xticks=None, xticklabels=None, yticks=None,
yticklabels=None, aspect='equal', rotation=45,
*args, **kwargs):
import itertools
if ax is None:
ax = plt.gca()
n = C.shape[0]
# create rotation/scaling matrix
t = np.array([[1, .5], [-1, .5]])
# create coordinate matrix and transform it
product = itertools.product(range(n, -1, -1), range(0, n + 1, 1))
A = np.dot(np.array([(ii[1], ii[0]) for ii in product]), t)
# plot
ax.pcolormesh((2 * A[:, 1].reshape(n + 1, n + 1) - n),
A[:, 0].reshape(n + 1, n + 1),
np.flipud(C), *args, **kwargs)
xticks = np.linspace(0, n - 1, n, dtype=int) if xticks is None else xticks
yticks = np.linspace(0, n - 1, n, dtype=int) if yticks is None else yticks
if xticks is not None:
xticklabels = xticks if xticklabels is None else xticklabels
for tick, label, in zip(xticks, xticklabels):
ax.scatter(-n + tick + .5, tick + .5, marker='x', color='k')
ax.text(-n + tick + .5, tick + .5, label,
horizontalalignment='right', rotation=-rotation)
if yticks is not None:
yticklabels = yticks if yticklabels is None else yticklabels
for tick, label, in zip(yticks, yticklabels):
ax.scatter(tick + .5, n - tick - .5, marker='x', color='k')
ax.text(tick + .5, n - tick - .5, label,
horizontalalignment='left', rotation=rotation)
if aspect:
ax.set_aspect(aspect)
ax.set_xlim(-n, n)
ax.set_ylim(-n, n)
ax.plot([-n, 0, n, 0., -n], [0, n, 0, -n, 0], color='k')
ax.axis('off')
return ax
也許如果你在3D情節中這樣做?
http://matplotlib.1069221.n5.nabble.com/How-to-rotate-a-3D-plot-td19185.html
axes3d.view_init(elev, azim)
這篇文章表明你只能“手工”完成。
可以繪制它,但您必須手動完成所有轉換/旋轉,包括將軸繪制為Line2D實例並將標簽繪制為文本實例(例如,參見檔案中的“Scatter3D”示例)。 目前,沒有簡單的內置方法。 在計划的軸處理重構中,
你看過PIL了嗎?
此代碼將旋轉圖像。 因此,如果您首先將繪圖輸出為文件作為圖像,那么您可以這樣做
import Image
img = Image.open("plot.jpg")
img2 = img.rotate(45)
img2.show()
img2.save("rotate.jpg")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.