2016-12-05 42 views
1

plt.margins適用於包含int或float值形式的數據的軸自動縮放的軸,詳見Add margin when plots run against the edge of the graph。然而,似乎沒有繪製其他值,諸如串標記或大熊貓數據幀索引時的工作:matplotlib中的自動縮放非數值軸

df = pd.DataFrame([0,3,2,6]) 
ax = df.plot(marker='o', ls='') 
ax.margins(0.05) 

enter image description here

只有y軸重新縮放,而不是x軸自然,還有一個X範圍內,並用ax.set_xlim()手動將其設置爲合理值,揭示了截短的數據點在圖中以上:

df = pd.DataFrame([0,3,2,6]) 
ax = df.plot(marker='o', ls='') 
ax.margins(0.05) 
ax.set_xlim(-0.1, 3.1) 

enter image description here

是否可以使用字符串標籤或熊貓數據框索引自動縮放軸?如果是這樣,我會怎麼做呢?

回答

0

您知道x軸的縮放比例,0與您的數據幀的長度減去1

ax.set_xlim(-0.1, len(df) - 0.9) 

將是一個合適的「autoscale」函數。

import pandas as pd 
import matplotlib.pyplot as plt 
import random 

df = pd.DataFrame([random.randrange(1, 10) for i in range(random.randrange(5, 15))]) 
ax = df.plot(marker='o', ls='') 
ax.margins(0.05) 
ax.set_xlim(-0.1, len(df) - 0.9) 
plt.show() 
0

你可以編寫自己的autoscale()函數。

import matplotlib.pyplot as plt 
import pandas as pd 

def automargin(ax=None, marginx=0.1, marginy=0.1, relative=False): 
    if ax == None: 
     ax=plt.gca() 
    xlim=ax.get_xlim() 
    ylim = ax.get_ylim() 
    if relative: 
     dx = xlim[1] - xlim[0]; dy = ylim[1] - ylim[0] 
     ax.set_xlim([xlim[0]-dx*marginx, xlim[1]+dx*marginx]) 
     ax.set_ylim([ylim[0]-dy*marginy, ylim[1]+dy*marginy]) 
    else: 
     ax.set_xlim([xlim[0]-marginx, xlim[1]+marginx]) 
     ax.set_ylim([ylim[0]-marginy, ylim[1]+marginy]) 


df = pd.DataFrame({"x": [0,1,2,3], "y" : [9,4,7,5]}) 
ax = df.plot(marker='o', ls='') 

#Try some of the following: 
automargin() 
automargin(ax) 
automargin(ax, relative=True) 
automargin(ax, marginy=0.5) 
automargin(ax, marginx=1, marginy=0.5) 
automargin(ax, marginx=0.05, marginy=0.05, relative=True) 

plt.show()