說明:此貼會不定期進行更新!
設置1:圖像的大小設置。
如果已經存在figure對象,可以通過以下代碼設置尺寸大小:
f.set_figheight(15)
f.set_figwidth(15)
若果通過.sublots()命令來創建新的figure對象, 可以通過設置figsize參數達到目的。
f, axs = plt.subplots(2,2,figsize=(15,15))
設置2:刻度和標注特殊設置
描述如下:在X軸標出一些重要的刻度點,當然實現方式有兩種:直接在X軸上標注和通過注釋annotate的形式標注在合適的位置。
其中第一種的實現並不是很合適,此處為了學習的目的一並說明下。
先說第一種:

正常X軸標注不會是這樣的,為了說明此問題特意標注成這樣,如此看來 0.3 和 0.4的標注重疊了,當然了解決重疊的問題可以通過改變figure 的size實現,顯然此處並不想這樣做。
怎么解決呢,那就在 0.3 和 0.4之間再設置一個刻度,有了空間后不顯示即可。
代碼如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 3))
ax = fig.add_subplot(1, 1, 1, frameon=False)
ax.set_xlim(-0.015, 1.515)
ax.set_ylim(-0.01, 1.01)
ax.set_xticks([0, 0.3, 0.4, 1.0, 1.5])
#增加0.35處的刻度並不標注文本,然后重新標注0.3和0.4處文本
ax.set_xticklabels([0.0, "", "", 1.0, 1.5])
ax.set_xticks([0.35], minor=True)
ax.set_xticklabels(["0.3 0.4"], minor=True)
#上述設置只是增加空間,並不想看到刻度的標注,因此次刻度線不予顯示。
for line in ax.xaxis.get_minorticklines():
line.set_visible(False)
ax.grid(True)
plt.show()
最終圖像形式如下:

當然最合理的方式是采用注釋的形式,比如:

代碼如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# Plot a sinc function
delta=2.0
x=np.linspace(-10,10,100)
y=np.sinc(x-delta)
# Mark delta
plt.axvline(delta,ls="--",color="r")
plt.annotate(r"$\delta$",xy=(delta+0.2,-0.2),color="r",size=15)
plt.plot(x,y)
設置3:增加X軸與Y軸間的間隔,向右移動X軸標注一點點即可
顯示效果對比:
設置前:

設置后:

兩張的圖像的差別很明顯,代碼如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
plot_data=[1.7,1.7,1.7,1.54,1.52]
xdata = range(len(plot_data))
labels = ["2009-June","2009-Dec","2010-June","2010-Dec","2011-June"]
ax.plot(xdata,plot_data,"b-")
ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)
ax.set_yticks([1.4,1.6,1.8])
# grow the y axis down by 0.05
ax.set_ylim(1.35, 1.8)
# expand the x axis by 0.5 at two ends
ax.set_xlim(-0.5, len(labels)-0.5)
plt.show()
設置4:移動刻度標注
上圖說明需求:

通過設置 set_horizontalalignment()來控制標注的左右位置:
for tick in ax2.xaxis.get_majorticklabels():
tick.set_horizontalalignment("left")
當然標注文本的上下位置也是可以控制的,比如:
ax2.xaxis.get_majorticklabels()[2].set_y(-.1)
當然控制刻度標注的上下位置也可以用labelpad參數進行設置:
pl.xlabel("...", labelpad=20)
或:
ax.xaxis.labelpad = 20
具體設置請查閱官方文檔,完整的代碼如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import datetime
# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365*5)])
data = np.sin(np.arange(365*5)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365*5) /3
# creates fig with 2 subplots
fig = plt.figure(figsize=(10.0, 6.0))
ax = plt.subplot2grid((2,1), (0, 0))
ax2 = plt.subplot2grid((2,1), (1, 0))
## plot dates
ax2.plot_date( dates, data )
# rotates labels
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-45 )
# shift labels to the right
for tick in ax2.xaxis.get_majorticklabels():
tick.set_horizontalalignment("right")
plt.tight_layout()
plt.show()
設置5:調整圖像邊緣及圖像間的空白間隔
圖像外部邊緣的調整可以使用plt.tight_layout()進行自動控制,此方法不能夠很好的控制圖像間的間隔。
如果想同時控制圖像外側邊緣以及圖像間的空白區域,使用命令:
plt.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8,hspace=0.2, wspace=0.3)
設置6:子圖像統一標題設置。
效果如下(subplot row i):

思路其實創建整個的子圖像,然后將圖像的刻度、標注等部分作不顯示設置,僅僅顯示圖像的 title。
代碼如下:
import matplotlib.pyplot as plt
fig, big_axes = plt.subplots(figsize=(15.0, 15.0) , nrows=3, ncols=1, sharey=True)
for row, big_ax in enumerate(big_axes, start=1):
big_ax.set_title("Subplot row %s \n" % row, fontsize=16)
# Turn off axis lines and ticks of the big subplot
# obs alpha is 0 in RGBA string!
big_ax.tick_params(labelcolor=(0,0,0,0), top='off', bottom='off', left='off', right='off')
# removes the white frame
big_ax._frameon = False
for i in range(1,10):
ax = fig.add_subplot(3,3,i)
ax.set_title('Plot title ' + str(i))
fig.set_facecolor('w')
plt.tight_layout()
plt.show()
設置7:圖像中標記線和區域的繪制
效果如下:

代碼如下:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(-1, 2, .01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)
# draw a thick red hline at y=0 that spans the xrange
l = plt.axhline(linewidth=4, color='r')
# draw a default hline at y=1 that spans the xrange
l = plt.axhline(y=1)
# draw a default vline at x=1 that spans the yrange
l = plt.axvline(x=1)
# draw a thick blue vline at x=0 that spans the upper quadrant of
# the yrange
l = plt.axvline(x=0, ymin=0.75, linewidth=4, color='b')
# draw a default hline at y=.5 that spans the middle half of
# the axes
l = plt.axhline(y=.5, xmin=0.25, xmax=0.75)
p = plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
p = plt.axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
plt.axis([-1, 2, -1, 2])
plt.show()
參考:####
- http://stackoverflow.com/questions/16162514/how-can-i-move-a-tick-label-onlywithout-moving-corresponding-tick
- http://stackoverflow.com/questions/28615887/how-to-move-a-ticks-label-in-matplotlib
- http://stackoverflow.com/questions/31928209/matplotlib-fixed-spacing-between-left-edge-of-figure-and-y-axis
- http://stackoverflow.com/questions/6406368/matplotlib-move-x-axis-label-downwards-but-not-x-axis-ticks
- http://matplotlib.org/examples/pylab_examples/axhspan_demo.html
