0

I have this code, and would like to display x & y axis data when hovering over the points:

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)

I would like to display time and temperature data while hovering please.

0

2 Answers 2

2

To display time and temperature data when hovering over points in your bar graph, you can use the mplcursors library. This library allows you to add interactive data labels to your Matplotlib plots.

pip install mplcursors

Here is how you can modify your code

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)
Sign up to request clarification or add additional context in comments.

3 Comments

HI Mishal, thank you, how do I include the timestamp to be displayed with the temperature as well please?
@Ashu you can modify the lambda function inside the cursor.connect method to include both the timestamp and temperature. Like this cursor.connect("add", lambda sel: sel.annotation.set_text(f"Time: {sel.target[0]}\nTemperature: {sel.target[1]:.2f}"))
Hi @Mishal, thanks for your help. Just another thing, the time only displays seconds, can it display the hour and seconds ( if not the date) please? Also I have added as follows so the seconds don't jump decimal places: (f"Time: {sel.target[0]:.0f}
0

To enable interactive hovering over the data points in a Matplotlib plot, you'd typically need an interactive backend and additional libraries. One popular choice is plotly, but in this solution, I'll guide you on how to use mplcursors, which is a utility for Matplotlib to provide interactivity.

Here's how you can modify your code:

  1. First, you'll need to install mplcursors:
pip install mplcursors
  1. Then you have to modify your code to include mplcursors and display hover information:
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)

Now, when you hover over the bars in your plot, a tooltip will display the x and y values (i.e., time and temperature).

1 Comment

thanks for your answer, I have since modified as follows so the label doesn't stay on the screen even after mouse is pointed away from the plot: mplcursors.cursor(ax, hover=mplcursors.HoverMode.Transient).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.