3

In Matplotlib, it is possible, using the following code:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1234)
fig, ax = plt.subplots(1)
x = 30*np.random.randn(10000)
mu = x.mean()
median = np.median(x)
sigma = x.std()
textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma)

ax.hist(x, 50)
# these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# place a text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)

to create the following histogram, with a text label:

enter image description here

However, in Plotly, I could not find how to create a similar label on a plot. It seems like any annotation must be attached to a data point. Is the addition of a general text label to a plot, such as in the above example, possible using Plotly?

1 Answer 1

1

You can give a name to your trace which would be the legend you want to show. Please note that you also need to add showlegend: true to your layout if you only have one trace.

The label can contain LaTeX code. You would need to import the MathJax library and escape each backslash.

Alternatively you can add an annotation to your layout, e.g.

annotations: [
    {
      x: -0.7,
      y: 800 ,
      text: '$\\mu = 0\\\\ \\sigma = 1$',
      showarrow: false,
    }]

var numbers = [];
var total = 100000;
for (var i = 0; i < total; i++) {
  numbers[i] =  ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3;
}
var data = [{
  x: numbers,
  name: '$\\mu = 0\\\\ \\sigma = 1$',
  type: 'histogram',
}];
var layout = {showlegend: true, annotations: [
    {
      x: -0.8,
      y: 800 ,
      text: '$\\mu = 0\\\\ \\sigma = 1$',
      showarrow: false,
    }]};
Plotly.newPlot('myDiv', data, layout);
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Note from the future: cdn.mathjax.org is nearing its end-of-life, check mathjax.org/cdn-shutting-down for migration tips.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.