📅  最后修改于: 2023-12-03 15:18:36.152000             🧑  作者: Mango
Plotly is a data visualization library used to create interactive graphs and charts. When creating a heatmap in Plotly, there are two ways to add information about each data point: using hovertemplate or hover text. Both methods have their advantages and can be used depending on the specific needs of your visualization.
A hovertemplate is a text string that defines how each point’s hover label should appear. It is specified in the trace object’s hovertemplate
attribute. The hovertemplate can include placeholders for the data that will be displayed when the user hovers over a data point. For example, the hovertemplate '{x}, {y}, {z}' would display the x, y, and z values of a data point when the user hovers over it.
Using a hovertemplate allows for more control over the formatting and content of the hover label. You can add custom text and formatting, and you can use mathematical expressions to calculate values that will be displayed in the hover label.
Hover text, on the other hand, is a list or array of strings that specifies the text to be displayed for each data point when the user hovers over it. It is specified in the trace object’s hovertext
attribute. Hover text is useful when you want to display simple text information about each data point, such as the name of the data point or its category.
Hover text is easier to use than hovertemplate, as you do not need to write any code or mathematical expressions. You can simply provide a list of strings to be displayed when the user hovers over a data point.
In summary, hovertemplate is more powerful and flexible than hover text, as it allows you to customize the hover label more extensively. Hover text, on the other hand, is simpler to use and more appropriate for displaying simple text information.
When choosing between hovertemplate and hover text, consider the complexity of the information you want to display and how much control you need over the formatting and content of the hover label.
# Using Hover Template
import plotly.graph_objects as go
import numpy as np
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = ['Morning', 'Afternoon', 'Evening']
z = np.random.randint(10, size=(len(y), len(x)))
hovertemplate = 'Day: %{x}<br>Time: %{y}<br>Value: %{z}'
fig = go.Figure(data=go.Heatmap(z=z, x=x, y=y, hovertemplate=hovertemplate))
fig.show()
# Using Hover Text
import plotly.graph_objects as go
import numpy as np
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = ['Morning', 'Afternoon', 'Evening']
z = np.random.randint(10, size=(len(y), len(x)))
hover_text = [['{}, {}: {}'.format(x_val, y_val, z_val) for x_val, z_val in zip(x, y_row)] for y_row in z]
fig = go.Figure(data=go.Heatmap(z=z, x=x, y=y, hovertext=hover_text))
fig.show()