T2 - Plotting, printing, and saving

This tutorial provides a brief overview of options for plotting results, printing objects, and saving results.

Click here to open an interactive version of this notebook.

Global plotting configuration

HPVsim allows the user to set various options that apply to all plots. You can change the font size, default DPI, whether plots should be shown by default, etc. (for the full list, see hpv.options.help()). For example, we might want higher resolution, to turn off automatic figure display, close figures after they’re rendered, and to turn off the messages that print when a simulation is running. We can do this using built-in defaults for Jupyter notebooks (and then run a sim) with:

import hpvsim as hpv

hpv.options(jupyter=True, verbose=0) # Standard options for Jupyter notebook

sim = hpv.Sim()
sim.run()
HPVsim 2.2.6 (2026-04-17) — © 2023-2026 by the Gates Foundation
Loading location-specific demographic data for "nigeria"
Sim(<no label>; 1995.0 to 2030.0; pop: 20000 default; epi: 8.24814e+08⚙, 512386♋︎)

Printing objects

There are three levels of detail available for most objects (sims, multisims, scenarios, and people). The shortest is brief():

sim.brief()
Sim(<no label>; 1995.0 to 2030.0; pop: 20000 default; epi: 8.24814e+08⚙, 512386♋︎)

You can get more detail with summarize():

sim.summarize()
Simulation summary:
     824,814,324 total HPV infections
         512,386 total cancers
         275,606 total cancer deaths
           14.47 mean HPV prevalence (%)
           14.72 mean cancer incidence (per 100k)
           33.14 mean age of infection (years)
           46.65 mean age of cancer (years)
           49.93 mean age of cancer death (years)

Finally, to show the full object, including all methods and attributes, use disp():

sim.disp()
<hpvsim.sim.Sim at 0x710d8f380830>
[<class 'hpvsim.sim.Sim'>, <class 'hpvsim.base.BaseSim'>, <class 'hpvsim.base.ParsObj'>, <class 'hpvsim.base.FlexPretty'>, <class 'sciris.sc_printing.prettyobj'>]
————————————————————————————————————————————————————————————————————————
Methods:
  _brief()                get_intervention()      reset_layer_pars()      
  _disp()                 get_interventions()     result_keys()           
  _get_ia()               get_t()                 result_types()          
  brief()                 init_analyzers()        run()                   
  compute_age_mean()      init_genotypes()        save()                  
  compute_fit()           init_hiv()              set_metadata()          
  compute_results()       init_immunity()         shrink()                
  compute_states()        init_interventions()    step()                  
  compute_summary()       init_people()           summarize()             
  copy()                  init_results()          to_df()                 
  disp()                  init_states()           to_excel()              
  export_pars()           init_time_vecs()        to_json()               
  export_results()        initialize()            update_pars()           
  finalize()              layer_keys()            validate_dt()           
  finalize_analyzers()    load()                  validate_init_condi...  
  get_analyzer()          load_data()             validate_layer_pars()   
  get_analyzers()         plot()                  validate_pars()         
————————————————————————————————————————————————————————————————————————
Properties:
  n                       
————————————————————————————————————————————————————————————————————————
 _default_ver: None
   _orig_pars: {'n_agents': 20000, 'total_pop': None, 'pop_scale':
               5468.3692, 'ms_ [...]
    analyzers: []
 art_datafile: None
     complete: True
      created: None
         data: None
     datafile: None
 hiv_datafile: None
       hivsim: <hpvsim.hiv.HIVsim at 0x710d8f381550>

  initialized: True
interventions: []
        label: None
         npts: 144
         pars: {'n_agents': 20000, 'total_pop': None, 'pop_scale':
               5468.3692, 'ms_ [...]
       people: People(n=68376; layers: m, c)
      popdict: None
      popfile: None
     res_npts: 36
     res_tvec: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
               12, 13, 14,  [...]
  res_yearvec: array([1995., 1996., 1997., 1998., 1999., 2000., 2001.,
               2002., 2003 [...]
      resfreq: 4
      results: #0. 'infections':
               <hpvsim.base.Result at 0x710d8f381010>
               [<class 'h [...]
results_ready: True
short_summary: #0: 'total HPV infections':             824814324.5
               #1: 'total canc [...]
      summary: #0. 'infections':            27453947.0
               #1. 'cins':                 [...]
            t: 143
         tvec: array([  0,   1,   2,   3,   4,   5,   6,   7,   8,
               9,  10,  11,  [...]
        years: array([1995., 1996., 1997., 1998., 1999., 2000., 2001.,
               2002., 2003 [...]
      yearvec: array([1995.  , 1995.25, 1995.5 , 1995.75, 1996.  ,
               1996.25, 1996.5 [...]
————————————————————————————————————————————————————————————————————————

Plotting options

While a sim can be plotted using default settings simply by sim.plot(), this is just a small fraction of what’s available. First, note that results can be plotted directly using e.g. Matplotlib. You can see what quantities are available for plotting with sim.results.keys() (remember, it’s just a dict). A simple example of plotting using Matplotlib is:

import pylab as plt # Shortcut for import matplotlib.pyplot as plt
plt.plot(sim.results['year'], sim.results['infections']);

However, as you can see, this isn’t ideal since the default formatting is…not great. (Also, note that each result is a Result object, not a simple Numpy array; like a pandas dataframe, you can get the array of values directly via e.g. sim.results.infections.values.)

An alternative, you can also select one or more quantities to plot with the first (to_plot) argument, e.g.

sim.plot(to_plot=['infections', 'hpv_incidence']);

While we can save this figure using Matplotlib’s built-in savefig(), if we use HPVsim’s hpv.savefig() we get a couple of advantages:

hpv.savefig('my-fig.png')
'my-fig.png'
<Figure size 672x480 with 0 Axes>

First, it saves the figure at higher resolution by default (which you can adjust with the dpi argument). But second, it stores information about the code that was used to generate the figure as metadata, which can be loaded later. Made an awesome plot but can’t remember even what script you ran to generate it, much less what version of the code? You’ll never have to worry about that again.

hpv.get_png_metadata('my-fig.png')
HPVsim version: 2.2.6
HPVsim branch: quarto
HPVsim hash: 9e21854
HPVsim date: 2026-04-18 02:28:39 UTC
HPVsim caller branch: quarto
HPVsim caller hash: 9e21854
HPVsim caller date: 2026-04-18 02:28:39 UTC
HPVsim caller filename: /home/cliffk/idm/hpvsim/hpvsim/misc.py
HPVsim current time: 2026-Apr-17 22:32:35
HPVsim calling file: /tmp/ipykernel_838472/1797766398.py

Customizing plots

We saw above how to set default plot configuration options for Jupyter. HPVsim provides a lot of flexibility in customizing the appearance of plots as well. There are three different levels at which you can set plotting options: global, just for HPVsim, or just for the current plot. To give an example with changing the figure DPI: - Change the setting globally (for both HPVsim and Matplotlib): sc.options(dpi=150) or pl.rc('figure', dpi=150) (where sc is import sciris as sc) - Change for HPVsim plots, but not for Matplotlib plots: hpv.options(dpi=150) - Change for the current HPVsim plot, but not other HPVsim plots: sim.plot(dpi=150)

The easiest way to change the style of HPVsim plots is with the style argument. For example, to plot using a built-in Matplotlib style would simply be:

sim.plot(style='ggplot');

In addition to the default style ('hpvsim'), there is also a “simple” style. You can combine built-in styles with additional overrides, including any valid Matplotlib commands:

sim.plot(style='simple', legend_args={'frameon':True}, style_args={'ytick.direction':'in'});

Although most style handling is done automatically, you can also use it yourself in a with block, e.g.:

import numpy as np
with hpv.options.with_style(fontsize=6):
    sim.plot() # This will have 6 point font
    plt.figure(); plt.plot(np.random.rand(20), 'o') # So will this

Saving options

Saving sims is also pretty simple. The simplest way to save is simply

sim.save('my-sim.sim')
'/home/cliffk/idm/hpvsim/docs/tutorials/my-sim.sim'

Technically, this saves as a gzipped pickle file (via sc.saveobj() using the Sciris library). By default this does not save the people in the sim since they are very large (and since, if the random seed is saved, they can usually be regenerated). If you want to save the people as well, you can use the keep_people argument. For example, here’s what it would look like to create a sim, run it halfway, save it, load it, change the overall transmissibility (beta), and finish running it:

sim_orig = hpv.Sim(start=2000, end=2030, label='Load & save example')
sim_orig.run(until='2015')
sim_orig.save('my-half-finished-sim.sim') # Note: HPVsim always saves the people if the sim isn't finished running yet

sim = hpv.load('my-half-finished-sim.sim')
sim['beta'] *= 0.3
sim.run()
sim.plot(['infections', 'hpv_incidence', 'cancer_incidence']);
Loading location-specific demographic data for "nigeria"

Aside from saving the entire simulation, there are other export options available. You can export the results and parameters to a JSON file (using sim.to_json()), but probably the most useful is to export the results to an Excel workbook, where they can easily be stored and processed with e.g. Pandas:

import pandas as pd

sim.to_excel('my-sim.xlsx')
df = pd.read_excel('my-sim.xlsx')
print(df)
Object saved to /home/cliffk/idm/hpvsim/docs/tutorials/my-sim.xlsx.
    year   t   infections          cins       cancers  cancer_deaths  \
0   2000   0  29432950.50  3.191645e+05      0.000000       0.000000   
1   2001   1  24800701.50  6.345888e+05      0.000000       0.000000   
2   2002   2  24262734.50  7.237304e+05      0.000000       0.000000   
3   2003   3  24298267.50  8.191058e+05   1246.736328       0.000000   
4   2004   4  25373577.50  8.110020e+05   1870.104492       0.000000   
5   2005   5  25192177.50  1.075933e+06   2493.472656       0.000000   
6   2006   6  25499498.50  1.063466e+06   3116.840820       0.000000   
7   2007   7  24237801.00  1.000506e+06   4986.945312       0.000000   
8   2008   8  24950311.00  1.012350e+06   8103.786133       0.000000   
9   2009   9  24485901.00  8.540144e+05   7480.417969       0.000000   
10  2010  10  24741482.00  1.061596e+06   7480.417969     623.368164   
11  2011  11  24876753.50  8.365601e+05  14337.467773    2493.472656   
12  2012  12  25190930.00  8.758322e+05  12467.363281    2493.472656   
13  2013  13  23411838.50  8.976501e+05   8103.786133    2493.472656   
14  2014  14  23471681.00  9.119876e+05  17454.308594    1870.104492   
15  2015  15  18640577.00  9.250783e+05  13090.731445    4986.945312   
16  2016  16  18196115.50  8.783257e+05  24934.726562    6857.049805   
17  2017  17  17175039.50  8.770790e+05  18077.676758    8103.786133   
18  2018  18  16574735.25  8.440405e+05  19324.413086   11220.626953   
19  2019  19  16471880.50  7.162500e+05  20571.149414    8727.154297   
20  2020  20  16170793.75  7.293407e+05  23064.622070   10597.258789   
21  2021  21  15114184.50  6.520431e+05  18077.676758   11843.995117   
22  2022  22  14270143.50  6.557833e+05  19324.413086   16207.572266   
23  2023  23  14301312.50  6.071606e+05  18701.044922   15584.204102   
24  2024  24  14079393.75  6.539132e+05  13090.731445   19947.781250   
25  2025  25  13768956.00  6.713675e+05  17454.308594    8727.154297   
26  2026  26  13395558.25  5.292396e+05  21194.517578   22441.253906   
27  2027  27  13011563.50  6.046671e+05  21817.885742   12467.363281   
28  2028  28  12520349.75  6.963022e+05  26804.831055   13090.731445   
29  2029  29  12534687.50  4.856038e+05  18077.676758   13090.731445   
30  2030  30  12262898.50  5.036815e+05  21817.885742   12467.363281   

    reinfections  reactivations  n_susceptible  n_infectious  ...  \
0   1.035415e+07              0      348562496      22623898  ...   
1   1.648248e+07              0      358287040      22547848  ...   
2   1.704912e+07              0      367606400      23155632  ...   
3   1.803903e+07              0      378315872      23915520  ...   
4   1.907569e+07              0      388794688      24581276  ...   
5   1.925148e+07              0      400040224      24798208  ...   
6   1.982498e+07              0      412021344      25291292  ...   
7   1.899216e+07              0      424650816      25538146  ...   
8   1.964108e+07              0      437049632      25972010  ...   
9   1.952826e+07              0      450944512      25616068  ...   
10  1.960867e+07              0      464920448      25843596  ...   
11  1.970654e+07              0      478572192      26255018  ...   
12  2.008056e+07              0      492741312      26480678  ...   
13  1.934872e+07              0      507995136      26329200  ...   
14  1.906509e+07              0      523242752      26322964  ...   
15  1.500198e+07              0      541681920      23843832  ...   
16  1.495460e+07              0      557085440      22890702  ...   
17  1.387056e+07              0      572519936      22227438  ...   
18  1.334507e+07              0      588116608      21535500  ...   
19  1.315556e+07              0      602329408      21231920  ...   
20  1.298850e+07              0      616560960      20624758  ...   
21  1.210893e+07              0      630755072      20328656  ...   
22  1.131538e+07              0      645603648      19480876  ...   
23  1.127174e+07              0      659398784      19494590  ...   
24  1.144005e+07              0      674845824      19099998  ...   
25  1.102863e+07              0      689507392      18930442  ...   
26  1.081419e+07              0      704374784      18578238  ...   
27  1.052308e+07              0      719834240      17893156  ...   
28  9.989475e+06              0      735187840      17447448  ...   
29  9.735140e+06              0      750267136      17336488  ...   
30  9.627922e+06              0      765745344      17011092  ...   

    cum_cin_treated  cum_cancer_treatments  cum_cancer_treated  \
0                 0                      0                   0   
1                 0                      0                   0   
2                 0                      0                   0   
3                 0                      0                   0   
4                 0                      0                   0   
5                 0                      0                   0   
6                 0                      0                   0   
7                 0                      0                   0   
8                 0                      0                   0   
9                 0                      0                   0   
10                0                      0                   0   
11                0                      0                   0   
12                0                      0                   0   
13                0                      0                   0   
14                0                      0                   0   
15                0                      0                   0   
16                0                      0                   0   
17                0                      0                   0   
18                0                      0                   0   
19                0                      0                   0   
20                0                      0                   0   
21                0                      0                   0   
22                0                      0                   0   
23                0                      0                   0   
24                0                      0                   0   
25                0                      0                   0   
26                0                      0                   0   
27                0                      0                   0   
28                0                      0                   0   
29                0                      0                   0   
30                0                      0                   0   

    cancer_mortality    n_alive       cdr       cbr  hpv_prevalence  \
0           0.000000  124214208  0.016310  0.043360        0.182136   
1           0.000000  127442000  0.013163  0.042408        0.176926   
2           0.000000  130848712  0.013497  0.042257        0.176965   
3           0.000000  134483568  0.011829  0.042227        0.177832   
4           0.000000  138099712  0.011858  0.042070        0.177997   
5           0.000000  141841184  0.013664  0.041927        0.174831   
6           0.000000  145753440  0.010508  0.041913        0.173521   
7           0.000000  149782880  0.010767  0.041660        0.170501   
8           0.000000  153921440  0.010959  0.041593        0.168735   
9           0.000000  158216432  0.011840  0.041251        0.161905   
10          0.779454  162677248  0.010216  0.040963        0.158864   
11          3.035040  167264624  0.011028  0.040623        0.156967   
12          2.955695  171919936  0.011665  0.039921        0.154029   
13          2.877533  176605152  0.012403  0.039286        0.149085   
14          2.101135  181456224  0.010742  0.038785        0.145065   
15          5.457213  186265504  0.006874  0.038085        0.128010   
16          7.323326  190953216  0.010655  0.036824        0.119876   
17          8.446825  195789952  0.010707  0.035787        0.113527   
18         11.412197  200584896  0.011039  0.034807        0.107364   
19          8.684056  205209664  0.010210  0.033901        0.103465   
20         10.322361  209689216  0.010708  0.032969        0.098359   
21         11.299167  214110752  0.010411  0.032841        0.094945   
22         15.138723  218693120  0.009418  0.032495        0.089079   
23         14.260534  223233728  0.010137  0.032281        0.087328   
24         17.870906  228110352  0.008196  0.031837        0.083731   
25          7.656591  232939584  0.009540  0.031498        0.081268   
26         19.292916  237756960  0.009580  0.031148        0.078140   
27         10.504257  242645424  0.009431  0.030726        0.073742   
28         10.818051  247576896  0.009296  0.030391        0.070473   
29         10.605258  252598112  0.008961  0.030083        0.068633   
30          9.898883  257652384  0.009482  0.029638        0.066023   

    precin_prevalence  cin_prevalence  
0            0.057622        0.004356  
1            0.055229        0.010807  
2            0.054935        0.016171  
3            0.053854        0.020504  
4            0.052341        0.023398  
5            0.050582        0.028022  
6            0.048756        0.031626  
7            0.047692        0.031925  
8            0.046777        0.033243  
9            0.044964        0.030496  
10           0.043005        0.031061  
11           0.042685        0.029402  
12           0.041286        0.029350  
13           0.039763        0.028092  
14           0.038645        0.027532  
15           0.035458        0.027122  
16           0.033319        0.025459  
17           0.031271        0.024041  
18           0.029196        0.023611  
19           0.027636        0.023199  
20           0.026488        0.022630  
21           0.025253        0.021617  
22           0.023593        0.019948  
23           0.023241        0.018864  
24           0.022193        0.018575  
25           0.021437        0.018425  
26           0.020659        0.017353  
27           0.019162        0.016114  
28           0.018210        0.016624  
29           0.018066        0.015797  
30           0.017269        0.014358  

[31 rows x 58 columns]