2011-06-07 106 views
19

因爲它們被繪製在繪圖區域內,所以軸標記被許多matplotlib圖中的數據遮擋。更好的方法是繪製從軸向外延伸的刻度,這是R的繪圖系統ggplot中的默認值。在matplotlib中,如何繪製從軸向外的R型軸蜱?

從理論上講,這可以通過重新劃分與TICKDOWNTICKLEFT線的樣式爲x軸和y軸的刻度線進行分別蜱:

import matplotlib.pyplot as plt 
import matplotlib.ticker as mplticker 
import matplotlib.lines as mpllines 

# Create everything, plot some data stored in `x` and `y` 
fig = plt.figure() 
ax = fig.gca() 
plt.plot(x, y) 

# Set position and labels of major and minor ticks on the y-axis 
# Ignore the details: the point is that there are both major and minor ticks 
ax.yaxis.set_major_locator(mplticker.MultipleLocator(1.0)) 
ax.yaxis.set_minor_locator(mplticker.MultipleLocator(0.5)) 

ax.xaxis.set_major_locator(mplticker.MultipleLocator(1.0)) 
ax.xaxis.set_minor_locator(mplticker.MultipleLocator(0.5)) 

# Try to set the tick markers to extend outward from the axes, R-style 
for line in ax.get_xticklines(): 
    line.set_marker(mpllines.TICKDOWN) 

for line in ax.get_yticklines(): 
    line.set_marker(mpllines.TICKLEFT) 

# In real life, we would now move the tick labels farther from the axes so our 
# outward-facing ticks don't cover them up 

plt.show() 

但在實踐中,這只是一半因爲get_xticklinesget_yticklines方法只返回主要刻度線。次要的蜱仍然指向內部。

什麼是小蜱的解決方法?

回答

29

在你matplotlib的配置文件,matplotlibrc,您可以設置:

xtick.direction  : out  # direction: in or out 
ytick.direction  : out  # direction: in or out 

,這將吸引主要和次要蜱向外默認情況下,像R.對於單個程序,只需做:

>> from matplotlib import rcParams 
>> rcParams['xtick.direction'] = 'out' 
>> rcParams['ytick.direction'] = 'out' 
4

你可以得到未成年人在至少在兩個方面:

>>> ax.xaxis.get_ticklines() # the majors 
<a list of 20 Line2D ticklines objects> 
>>> ax.xaxis.get_ticklines(minor=True) # the minors 
<a list of 38 Line2D ticklines objects> 
>>> ax.xaxis.get_minorticklines() 
<a list of 38 Line2D ticklines objects> 

注意的是,38是因爲輕微的刻度線也已經在由MultipleLocator呼叫「主要」位置繪製。

+0

這樣做。謝謝。 – pash 2011-06-07 17:40:48