2017-02-09 84 views
0

我有以下幾行代碼來生成如下所示的繪圖。當我將鼠標移動到繪圖中的標記時,如何在彈出框中顯示繪圖數據

from matplotlib import pyplot as plt 
from mpldatacursor import datacursor 
from matplotlib import dates as mdates 
import datetime 

date = [datetime.date(2015, 7, 1), datetime.date(2015, 8, 1), datetime.date(2015, 9, 1), datetime.date(2015, 10, 1), datetime.date(2015, 11, 1), datetime.date(2015, 12, 1), datetime.date(2016, 1, 1), datetime.date(2016, 2, 1)] 
people = [0, 0, 0, 0, 0, 0, 122, 38] 

fig, ax1 = plt.subplots() 
ax2 = ax1.twinx() 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
lns1 = ax1.plot(date, people, 'ro') 
plt.gcf().autofmt_xdate() 

datacursor(ax1, hover=True, formatter='customer: {y:0.0f}'.format) 
plt.show() 

OUTPUT: enter image description here

我所試圖做的是,顯示彈出框,當我將鼠標懸停在該標記。但是用我的代碼,無論我移動光標,都會彈出窗口。

也有可能在該彈出窗口中顯示日期?

+0

什麼是'datacursor'?它從何而來?如果您自己編寫該函數,則需要使代碼可用,如果它是第三方函數,則鏈接到它並顯示如何導入它。 – ImportanceOfBeingErnest

+0

這是一個內置函數。我是通過https://github.com/joferkington/mpldatacursor來了解這個的。 – nas

+0

那你怎麼導入它呢?請[編輯]您的問題以合併此信息。 – ImportanceOfBeingErnest

回答

1

問題是,您已將datacursor附加到axes對象上,而不是圖形本身,因此無論您將鼠標移動到軸的任何位置,它都會被觸發。如果您將其附加到圖表上,則只會在您結束數據點時觸發。

datacursor(lns1, hover=True, formatter='customer: {y:0.0f}'.format) 

如果你想顯示在光標的日期,你可以從x軸得到主刻度標記的格式,如果你想指定使用的格式化程序爲您的數據光標

# Get the formatter that's being used on the axes 
xformatter = plt.gca().xaxis.get_major_formatter() 

# Apply it to your data cursor 
datacursor(lns1, hover=True, formatter= lambda **kwargs: xformatter(kwargs.get('x'))) 

一個不同於的格式,可以使用帶有自定義格式字符串的DateFormatter對象。

from matplotlib.dates import DateFormatter 

fmt = DateFormatter('%Y-%m-%d') 
datacursor(lns1, hover=True, formatter= lambda **kwargs: fmt(kwargs.get('x'))) 

更新

如果你希望客戶標籤和日期,你可以做

fmt = DateFormatter('%Y-%m-%d') 
datacursor(lns1, hover=True, formatter= lambda **kwargs: 'customer: {y:.0f}'.format(**kwargs) + 'date: ' + fmt(kwargs.get('x'))) 

作爲一個側面說明,datacursor沒有內置在像你提到的。它是mpldatacursor的一部分。

+0

是的,我明白了。我已經修復了它:)我正在尋找彈出的顯示日期 – nas

+1

@nas更新了關於如何做到這一點的一些細節 – Suever

+0

我怎樣才能在彈出的標籤。例如。 (客戶:40,日期:2017-2-3)。我嘗試過,但每次都會出現語法錯誤。感謝您的幫助 – nas

相關問題