如何在Python中的绘图上添加悬停模板

问题描述 投票:0回答:2

我有这个代码,并且想在将鼠标悬停在点上时显示 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)

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

python hover
2个回答
0
投票

要在 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 值(即时间和温度)。


0
投票

要将鼠标悬停在条形图中的点上时显示时间和温度数据,您可以使用 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"{sel.artist.get_label()}: {sel.target[1]:.2f}"))

plt.subplots_adjust(bottom=0.2)
plt.xlabel("Time")
plt.ylabel("Temperature")
plt.title('Temperature')
plt.show(block=True)
© www.soinside.com 2019 - 2024. All rights reserved.