Plots Plot Toolbox icon

Properties | Events

The Plot component is a Plotly Plot. Drag and drop onto your Form, or create one in code with the Plot constructor.

Plots are interactive - move the mouse over a plot to see the available tools.

# Create a plot

b = Plot()
A dashboard made up of Plot components.

A dashboard made up of Plot components.

Configuring plots

Plots are configured using utility classes from the plotly.graph_objs module. Display a plot by setting the data and layout properties of the Plot component. The data property should be set to a list of traces as described in the plotly documentation.

from plotly import graph_objs as go

# Plot some data
self.plot_1.data = [
  go.Scatter(
    x = [1, 2, 3],
    y = [3, 1, 6],
    marker = go.Marker(
      color= 'rgb(16, 32, 77)'
    )
  ),
  go.Bar(
    x = [1, 2, 3],
    y = [3, 1, 6],
    name = 'Bar Chart Example'
  )
]

The layout property should be set to a dictionary describing the layout of the plot. You can also set layout properties as attributes, such as self.plot_1.layout.yaxis.title = 'carbon emissions'.

# Configure the plot layout
self.plot_1.layout = {
  'title': 'Simple Example',
  'xaxis': {
    'title': 'time'
  }
}
self.plot_1.layout.yaxis.title = 'carbon emissions'
self.plot_1.layout.annotations = [
    go.Annotation(
      text = 'Simple annotation',
      x = 0,
      xref = 'paper',
      y = 0,
      yref = 'paper'
    )
]
A bar chart and a scatter plot on the same axis.

Handling events

You can handle events raised when the user clicks, selects or hovers over data points. The click, select, hover and unhover events all provide a points keyword argument. This is a list of dictionaries, each with the following keys:

  • curve_number - the index of the data series that was clicked.
  • point_number - the index of the data point that was clicked. Not available for histograms.
  • point_numbers - a list of indices of the points aggregated into the clicked bin. Only available for histograms.
  • x, y, z, lat, lon - the position of the point that was clicked, depending on the plot type.

For example, to print the x and y coordinates when a user hovers over a data point:

def plot_1_hover(self, points, **event_args):
  """This method is called when a data point is hovered."""
  print("User hovered over x:{} and y:{}".format(points[0]['x'], points[0]['y']))

Plots are interactive by default. Create a static plot by setting the interactive property to False.

See the Plotly documentation for more details and examples.

Matplotlib

Matplotlib is a popular plotting library for Python. In addition to interactive Plotly plots, Anvil can produce Matplotlib plots in server-side code.

We’re going to walk through a simple Matplotlib example that makes a graph like this:

A decaying cosine wave plotted using Matplotlib.

Matplotlib is available in Anvil’s Server Modules, if you choose the Full Python runtime. Once you’ve made a plot, call anvil.mpl_util.plot_image() to capture that plot as an Anvil Media object.

You can then return that image from your Server Module, where you can display it on your page (with the Image component), or offer it for download (with the Link component), or even add it to a database.

Let’s see an example. Here’s the server function that makes our plot:

@anvil.server.callable
def make_plot():
  # Make a nice wiggle
  x = np.arange(0.0, 5.0, 0.02)
  y = np.exp(-x) * np.cos(2*np.pi*x)
  
  # Plot it in the normal Matplotlib way
  plt.figure(1, figsize=(10,5))
  plt.plot(x, y, 'crimson')  
  
  # Return this plot as a PNG image
  return anvil.mpl_util.plot_image()

And here’s the client-side code to display that plot and make it downloadable:

    img = anvil.server.call('make_plot')
    
    self.image_1.source = img
    self.download_lnk.url = img

This produces the plot shown in the image above.

Click here to open the full source code for that example in your Anvil Editor: