matplotlib 如何在图上添加悬停模板[重复]

smdnsysy  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(124)

此问题已在此处有答案

How to add hovering annotations to a plot(13个回答)
29天前关闭
我有这样的代码,并希望在悬停在点上时显示x和y轴数据:

import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt

ts = ['25/02/2023 0:00', '25/02/2023 0:01', '25/02/2023 0:02', '25/02/2023 0:03', '25/02/2023 0:04', '25/02/2023 0:05', '25/02/2023 0:06', '25/02/2023 0:07', 
        '25/02/2023 0:08', '25/02/2023 0:09', '25/02/2023 0:10', '25/02/2023 0:11', '25/02/2023 0:12', '25/02/2023 0:13', '25/02/2023 0:14', '25/02/2023 0:15', 
        '25/02/2023 0:16', '25/02/2023 0:17', '25/02/2023 0:18', '25/02/2023 0:19', '25/02/2023 0:20', '25/02/2023 0:21', '25/02/2023 0:22', '25/02/2023 0:23', 
        '25/02/2023 0:24', '25/02/2023 0:25', '25/02/2023 0:26', '25/02/2023 0:27', '25/02/2023 0:28', '25/02/2023 0:29', '25/02/2023 0:30']

temp = ['0', '-21', '20', '30', '-40', '50', '6', '7', '8', '9', '10', '11', '12', '13', '14', 
        '15', '16', '17', '-18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', 
        '29', '68']

df = pd.DataFrame(list(zip(ts, temp)),
                  columns = ['ts', 'temp'])
df['temp']=df['temp'].astype(float)
df1 = df.reset_index()
df100 = pd.DataFrame(data=df1)
df100['ts'] = pd.to_datetime(df100['ts'])
df100['ts'] = df100['ts'].dt.strftime('%d-%m--%H:%M')

df100.plot.bar(x="ts", y="temp", rot=90, figsize=(12, 6))
plt.subplots_adjust(bottom=0.2)
plt.xlabel("Time")
plt.ylabel("temp")
plt.title('Temperature')
plt.show(block=True)

我想在悬停时显示时间和温度数据。

hyrbngr7

hyrbngr71#

要在将鼠标悬停在条形图中的点上时显示时间和温度数据,您可以使用mplcursors库。此库允许您向Matplotlib图添加交互式数据标签。

pip install mplcursors

下面是如何修改代码

import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import mplcursors

ts = ['25/02/2023 0:00', '25/02/2023 0:01', '25/02/2023 0:02', '25/02/2023 0:03', '25/02/2023 0:04', '25/02/2023 0:05', '25/02/2023 0:06', '25/02/2023 0:07', 
        '25/02/2023 0:08', '25/02/2023 0:09', '25/02/2023 0:10', '25/02/2023 0:11', '25/02/2023 0:12', '25/02/2023 0:13', '25/02/2023 0:14', '25/02/2023 0:15', 
        '25/02/2023 0:16', '25/02/2023 0:17', '25/02/2023 0:18', '25/02/2023 0:19', '25/02/2023 0:20', '25/02/2023 0:21', '25/02/2023 0:22', '25/02/2023 0:23', 
        '25/02/2023 0:24', '25/02/2023 0:25', '25/02/2023 0:26', '25/02/2023 0:27', '25/02/2023 0:28', '25/02/2023 0:29', '25/02/2023 0:30']

temp = ['0', '-21', '20', '30', '-40', '50', '6', '7', '8', '9', '10', '11', '12', '13', '14', 
        '15', '16', '17', '-18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', 
        '29', '68']

df = pd.DataFrame(list(zip(ts, temp)),
                  columns=['ts', 'temp'])
df['temp'] = df['temp'].astype(float)
df1 = df.reset_index()
df100 = pd.DataFrame(data=df1)
df100['ts'] = pd.to_datetime(df100['ts'])
df100['ts'] = df100['ts'].dt.strftime('%d-%m--%H:%M')

# create the bar plot
ax = df100.plot.bar(x="ts", y="temp", rot=90, figsize=(12, 6))

# add interactive data using mplcursors
cursor = mplcursors.cursor(ax, hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(f"Time: {sel.target[0]}\nTemperature: {sel.target[1]:.2f}"))

plt.subplots_adjust(bottom=0.2)
plt.xlabel("Time")
plt.ylabel("Temperature")
plt.title('Temperature')
plt.show(block=True)
ttvkxqim

ttvkxqim2#

要在Matplotlib图中的数据点上启用交互式悬停,通常需要一个交互式后端和其他库。一个流行的选择是plotly,但在此解决方案中,我将指导您如何使用mplcursors,这是Matplotlib提供交互性的实用程序。
下面是你可以修改你的代码的方法:
1.首先,您需要安装mplcursors

pip install mplcursors

1.然后你必须修改你的代码以包含mplcursors并显示悬停信息:

import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import mplcursors  # <--- Add this import

ts = [ ... ]  # your list remains unchanged

temp = [ ... ]  # your list remains unchanged

df = pd.DataFrame(list(zip(ts, temp)), columns=['ts', 'temp'])
df['temp'] = df['temp'].astype(float)
df1 = df.reset_index()
df100 = pd.DataFrame(data=df1)
df100['ts'] = pd.to_datetime(df100['ts'])
df100['ts'] = df100['ts'].dt.strftime('%d-%m--%H:%M')

ax = df100.plot.bar(x="ts", y="temp", rot=90, figsize=(12, 6))
plt.subplots_adjust(bottom=0.2)
plt.xlabel("Time")
plt.ylabel("temp")
plt.title('Temperature')

# Add interactivity with mplcursors
mplcursors.cursor(hover=True)

plt.show(block=True)

现在,当您将鼠标悬停在图中的条形图上时,工具提示将显示x和y值(即时间和温度)。

相关问题