2014-06-17 108 views
1

我散點圖來自熊貓數據框的值。我只想在值大於100時對點進行註解。我不知道如何去解決這個問題。如果功能從熊貓註釋

這裏是我的工作的代碼(這是可怕的,但我很新):

female_data = r'/home/jg/Desktop/hurricanedata_f.csv' 
female_df = read_csv(female_data) 

male_data = r'/home/jg/Desktop/hurricanedata_m.csv' 
male_df = read_csv(male_data) 

x = female_df['Year'] 
y = female_df['alldeaths'] 
z = female_df['Name'] 
y_mean = [np.mean(y) for i in x] 
a = male_df['Year'] 
b = male_df['alldeaths'] 
b_mean = [np.mean(b) for i in b] 

fig = plt.figure() 
ax = fig.add_subplot(1,1,1) 


ax.annotate('Agnes', xy=(1972,117)) 
ax1 = fig.add_subplot(1,1,1) 
ax1.scatter(x,y, label = 'female', color = 'r') 
ax2 = fig.add_subplot(1,1,1) 
ax2.scatter(a,b, label = 'male') 
ax3 = fig.add_subplot(1,1,1) 
ax3.plot(x, y_mean, linestyle='--', color = 'r') 
ax4 = fig.add_subplot(1,1,1) 
ax4.plot(a, b_mean, linestyle='--', color = 'blue') 

plt.title('Hurricanes') 
plt.xlabel('Year') 
plt.ylabel('Deaths') 
plt.legend(loc='upper right') 
plt.ylim([-5,300]) 
plt.xlim([1948,2020]) 

plt.show() 

回答

0

您可以遍歷所有的數據點,並檢查各大於100。然後,給這些點註釋。

import matplotlib.pyplot as plt 
import numpy as np 
import string 

# Fake data 
x = np.arange(10) 
y = 10*np.random.rand(10) + 95 
names = string.lowercase[:10] # first 10 lowercase letters 

# Plot data 
fig = plt.figure() 
ax = fig.add_subplot(1,1,1) 
ax.scatter(x,y) 

# Annonate points with y values greater than 100 
for xi, yi, iname in zip(x,y,names): # Loop over x and y values 
    if yi > 100: # Check if y is greater than 100 
     ax.annotate(iname, (xi, yi),size = 30) # Add an annoatation. 

plt.show() 

enter image description here

+0

感謝莫莉,即大部分運作良好。我可以使用相應的y值來註釋代碼,但不能使用相應的名稱(第三個df列)。如果我做ax.annotate(z [i],(xi,yi)),它會爲每個點分配相同的名稱(出於某種原因,這個點是== 20而不是> 100)。我一直在閱讀儘可能多的文檔,但我仍然沒有弄清楚。 –

+0

我改變了我的例子,爲每個點包含不同的標籤。希望這會有所幫助。 – Molly

+0

完美的工作!非常感謝。 –