如何使用matplotlib在python中的图形上打印时显示值



我已经使用panda读取了csv文件,使用matplotlib和funcAnimate绘制,延迟100ms。绘制时需要显示每个数据的值。

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd

plt.style.use('seaborn')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def animation(i):
HV = pd.read_csv('FCW_HV.csv')
lat_HV = []
lon_HV = []
lat_HV = HV[0:i]['Latitude(deg)']
lon_HV = HV[0:i][' Longitude(deg)']
ax.clear()
plt.title('FCW Scenario')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
ax.scatter(lon_HV, lat_HV,s=30, marker="s",label='HV')
plt.legend(loc='upper left');
animation = FuncAnimation(fig, func=animation, interval=100)
plt.show()

您可能想要使用在动画函数中更新的Text对象,例如:

long, lat = lon_HV[-1], lat_HV[-1]
text = f"({long:.1f}°, {lat:.1f}°)" # Format this however you want.
ax.text(0.95, 0.95, text, transform=ax.transAxes) # This transform will force the text to 
# stay in the top-right bottom of your figure.

我还建议您将HV = pd.read_csv('FCW_HV.csv')行移到动画之外,因为您只需要读取该文件一次。动画函数只需要对数据进行切片。

现在的代码是:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
plt.style.use('seaborn')
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
HV = pd.read_csv('FCW_HV.csv')

def animation(i):
lat_HV = HV[0:i+1]['Latitude(deg)']
lon_HV = HV[0:i+1][' Longitude(deg)']
ax.clear()
ax.set_title('FCW Scenario')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
long, lat = lon_HV[-1], lat_HV[-1]
text = f"({long:.1f}°, {lat:.1f}°)"
ax.text(0.95, 0.95, text, transform=ax.transAxes) 
ax.scatter(lon_HV, lat_HV,s=30, marker="s",label='HV')
ax.legend(loc='upper left');
animation = FuncAnimation(fig, func=animation, interval=100)
fig.show()

我修改了索引,使您的切片为[0:i+1],否则第一帧不包含任何数据,long, lat = ...失败并抛出IndexError。

最新更新