Pyplot: Display label values when mouse hover point

纵饮孤独 提交于 2021-01-28 12:42:38

问题


I have a very basic plot, for which I would like to add the ability to display values when mouse hovers over data points on the plot.

The code I use to create my line graph is as follows:

df_all['count'] = pd.to_numeric(df_all['count'])
cumulative = df_all['count'].cumsum()
cumulative.plot()

plt.plot()

print(plt.show())

Many thanks in advance


回答1:


Further to the comment regarding Plotly, here is a very simple example of how to plot a graph, with hoverable trends.

Example code:

import random
import pandas as pd
from plotly.offline import plot

# Create a random list of values.
vals = [random.randint(0, 10) for _ in range(100)]

# Create a test DataFrame.
df = pd.DataFrame({'count': vals})
df['cumsum'] = df['count'].cumsum()

Create the graph using Plotly:

# Plot the results.
traces = []
traces.append({'y': df['count'], 'name': 'Single Counts'})
traces.append({'y': df['cumsum'], 'name': 'Cumulative'})

plot({'data': traces})

Output:
As you can see, my cursor was hovering at x: 50, y: 248. The displayed text is highly configurable, as can be reviewed in the hovertext documentation.

TL;DR:
Given the extensive configuration capability Plotly provides, it's very easy to get lost in Dash, Plotly Express, Figure Factories, etc., and come to a conclusion of 'What solution do I really need?' - I thought it would be helpful to show a very stripped down (yet entirely functional) example of how to plot a graph with hoverable trends.




回答2:


This post uses mplcursors to show data when hover for a scatter plot. Could be a reference.



来源:https://stackoverflow.com/questions/64518034/pyplot-display-label-values-when-mouse-hover-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!