1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
|
# Plotting Functions
MultiQC plotting functions are held within `multiqc.plots` submodules.
To use them, simply import the modules you want, eg.:
```python
from multiqc.plots import bargraph, linegraph
```
Once you've done that, you will have access to the corresponding plotting
functions:
```python
bargraph.plot()
linegraph.plot()
scatter.plot()
table.plot()
beeswarm.plot()
heatmap.plot()
```
These have been designed to work in a similar manner to each other - you
pass a data structure to them, along with optional extras such as categories
and configuration options, and they return a string of HTML to add to the
report. You can add this to the module introduction or sections as described
above. For example:
```python
self.add_section (
name = 'Module Section',
anchor = 'mymod_section',
description = 'This plot shows some really nice data.',
helptext = 'This longer string (can be **markdown**) helps explain how to interpret the plot',
plot = bargraph.plot(self.parsed_data, categories, pconfig)
)
```
## Common options
All plots should as a minimum have a config with an `id` and a `title`.
MultiQC is written to work with sensible defaults, so won't complain if you
don't supply these, but it's good practice for usability (the ID is used as
a filename when exporting plots, and all plots should have a title when exported).
Plot titles should use the format _Module name: Plot name_ (this is partly for
ease of use within MegaQC and other downstream tools).
## Bar graphs
Simple data can be plotted in bar graphs. Many MultiQC modules make use
of stacked bar graphs. Here, the `bargraph.plot()` function comes to
the rescue. A basic example is as follows:
```python
from multiqc.plots import bargraph
data = {
'sample 1': {
'aligned': 23542,
'not_aligned': 343,
},
'sample 2': {
'not_aligned': 7328,
'aligned': 1275,
}
}
html_content = bargraph.plot(data)
```
To specify the order of categories in the plot, you can supply a list of
dictionary keys. This can also be used to exclude a key from the plot.
```python
cats = ['aligned', 'not_aligned']
html_content = bargraph.plot(data, cats)
```
If `cats` is given as a dict instead of a list, you can specify a nice name
and a colour too. Make it an OrderedDict to specify the order:
```python
from collections import OrderedDict
cats = OrderedDict()
cats['aligned'] = {
'name': 'Aligned Reads',
'color': '#8bbc21'
}
cats['not_aligned'] = {
'name': 'Unaligned Reads',
'color': '#f7a35c'
}
```
Finally, a third variable should be supplied with configuration variables for
the plot. The defaults are as follows:
```python
config = {
# Building the plot
'id': '<random string>', # HTML ID used for plot
'cpswitch': True, # Show the 'Counts / Percentages' switch?
'cpswitch_c_active': True, # Initial display with 'Counts' specified? False for percentages.
'cpswitch_counts_label': 'Counts', # Label for 'Counts' button
'cpswitch_percent_label': 'Percentages' # Label for 'Percentages' button
'logswitch': False, # Show the 'Log10' switch?
'logswitch_active': False, # Initial display with 'Log10' active?
'logswitch_label': 'Log10', # Label for 'Log10' button
'hide_zero_cats': True, # Hide categories where data for all samples is 0
# Customising the plot
'title': None, # Plot title - should be in format "Module Name: Plot Title"
'xlab': None, # X axis label
'ylab': None, # Y axis label
'labelSize': 8, # Axis label font size
'ymax': None, # Max y limit
'ymin': None, # Min y limit
'yCeiling': None, # Maximum value for automatic axis limit (good for percentages)
'yFloor': None, # Minimum value for automatic axis limit
'yMinRange': None, # Minimum range for axis
'yDecimals': True, # Set to false to only show integer labels
'ylab_format': None, # Format string for x axis labels. Defaults to {value}
'stacking': 'normal', # Set to None to have category bars side by side
'use_legend': True, # Show / hide the legend
'click_func': None, # Javascript function to be called when a point is clicked
'cursor': None, # CSS mouse cursor type.
'tt_decimals': 0, # Number of decimal places to use in the tooltip number
'tt_suffix': '', # Suffix to add after tooltip number
'tt_percentages': True, # Show the percentages of each count in the tooltip
'height': 512 # The default height of the plot, in pixels
}
```
> The keys `id` and `title` should always be passed as a minimum. The `id` is used
> for the plot name when exporting. If left unset, the Plot Export panel will call
> the filename `mqc_hcplot_gtucwirdzx.png` (with some other random string).
> Plots should always have titles, especially as they can stand by themselves
> when exported. The title should have the format `Modulename: Plot Name`
### Switching datasets
It's possible to have single plot with buttons to switch between different
datasets. To do this, give a list of data objects to the `plot` function
and specify the `data_labels` config option with the text to be used for the buttons:
```python
config = {
'data_labels': ['Reads', 'Bases']
}
html_content = bargraph.plot([data1, data2], pconfig=config)
```
You can also customise the y-axis label and min/max values for each dataset:
```python
config = {
'data_labels': [
{'name': 'Reads', 'ylab': 'Number of Reads'},
{'name': 'Bases', 'ylab': 'Number of Base Pairs', 'ymax':100}
]
}
```
If supplying multiple datasets, you can also supply a list of category
objects. Make sure that they are in the same order as the data.
Categories should contain data keys, so if you're supplying a list of two datasets,
you should supply a list of two sets of keys for the categories. MultiQC will try to
guess categories from the data keys if categories are missing.
For example, with two datasets supplied as above:
```python
cats = [
['aligned_reads','unaligned_reads'],
['aligned_base_pairs','unaligned_base_pairs'],
]
```
Or with additional customisation such as name and colour:
```python
from collections import OrderedDict
cats = [OrderedDict(), OrderedDict()]
cats[0]['aligned_reads'] = {'name': 'Aligned Reads', 'color': '#8bbc21'}
cats[0]['unaligned_reads'] = {'name': 'Unaligned Reads', 'color': '#f7a35c'}
cats[1]['aligned_base_pairs'] = {'name': 'Aligned Base Pairs', 'color': '#8bbc21'}
cats[1]['unaligned_base_pairs'] = {'name': 'Unaligned Base Pairs', 'color': '#f7a35c'}
html_content = bargraph.plot([data, data], cats, config)
```
Note that, as in this example, the plot data can be the same dictionary supplied twice.
### Interactive / Flat image plots
Note that the `bargraph.plot()` function can generate both interactive
JavaScript (HighCharts) powered report plots _and_ flat image plots made using
MatPlotLib. This choice is made within the function based on config variables
such as number of dataseries and command line flags.
Note that both plot types should come out looking pretty much identical. If
you spot something that's missing in the flat image plots, let me know.
## Line graphs
This base function works much like the above, but for two-dimensional
data, to produce line graphs. It expects a dictionary with sample identifiers,
each containing numeric `x:y` points. For example:
```python
from multiqc.plots import linegraph
data = {
'sample 1': {
'<x val 1>': '<y val 1>',
'<x val 2>': '<y val 2>'
},
'sample 2': {
'<x val 1>': '<y val 1>',
'<x val 2>': '<y val 2>'
}
}
html_content = linegraph.plot(data)
```
Additionally, a configuration dict can be supplied. The defaults are as follows:
```python
from multiqc.plots import linegraph
config = {
# Building the plot
'id': '<random string>', # HTML ID used for plot
'categories': False, # Set to True to use x values as categories instead of numbers.
'colors': dict() # Provide dict with keys = sample names and values colours
'smooth_points': None, # Supply a number to limit number of points / smooth data
'smooth_points_sumcounts': True, # Sum counts in bins, or average? Can supply list for multiple datasets
'logswitch': False, # Show the 'Log10' switch?
'logswitch_active': False, # Initial display with 'Log10' active?
'logswitch_label': 'Log10', # Label for 'Log10' button
'extra_series': None, # See section below
# Plot configuration
'title': None, # Plot title - should be in format "Module Name: Plot Title"
'xlab': None, # X axis label
'ylab': None, # Y axis label
'labelSize': 8, # Axis label font size
'xCeiling': None, # Maximum value for automatic axis limit (good for percentages)
'xFloor': None, # Minimum value for automatic axis limit
'xMinRange': None, # Minimum range for axis
'xmax': None, # Max x limit
'xmin': None, # Min x limit
'xLog': False, # Use log10 x axis?
'xDecimals': True, # Set to false to only show integer labels
'yCeiling': None, # Maximum value for automatic axis limit (good for percentages)
'yFloor': None, # Minimum value for automatic axis limit
'yMinRange': None, # Minimum range for axis
'ymax': None, # Max y limit
'ymin': None, # Min y limit
'yLog': False, # Use log10 y axis?
'yDecimals': True, # Set to false to only show integer labels
'yPlotBands': None, # Highlighted background bands. See http://api.highcharts.com/highcharts#yAxis.plotBands
'xPlotBands': None, # Highlighted background bands. See http://api.highcharts.com/highcharts#xAxis.plotBands
'yPlotLines': None, # Highlighted background lines. See http://api.highcharts.com/highcharts#yAxis.plotLines
'xPlotLines': None, # Highlighted background lines. See http://api.highcharts.com/highcharts#xAxis.plotLines
'xLabelFormat': '{value}', # Format string for the axis labels
'yLabelFormat': '{value}', # Format string for the axis labels
'tt_label': '{point.x}: {point.y:.2f}', # Use to customise tooltip label, eg. '{point.x} base pairs'
'tt_decimals': None, # Tooltip decimals when categories = True (when false use tt_label)
'tt_suffix': None, # Tooltip suffix when categories = True (when false use tt_label)
'pointFormat': None, # Replace the default HTML for the entire tooltip label
'click_func': function(){}, # Javascript function to be called when a point is clicked
'cursor': None # CSS mouse cursor type. Defaults to pointer when 'click_func' specified
'reversedStacks': False # Reverse the order of the category stacks. Defaults True for plots with Log10 option
'height': 512 # The default height of the plot, in pixels
}
html_content = linegraph.plot(data, config)
```
> The keys `id` and `title` should always be passed as a minimum. The `id` is used
> for the plot name when exporting. If left unset, the Plot Export panel will call
> the filename `mqc_hcplot_gtucwirdzx.png` (with some other random string).
> Plots should always have titles, especially as they can stand by themselves
> when exported. The title should have the format `Modulename: Plot Name`
### Switching datasets
You can also have a single plot with buttons to switch between different
datasets. To do this, just supply a list of data dicts instead (same
formats as described above). For example:
```python
data = [
{
'sample 1': { '<x val 1>': '<y val 1>', '<x val 2>': '<y val 2>' },
'sample 2': { '<x val 1>': '<y val 1>', '<x val 2>': '<y val 2>' }
},
{
'sample 1': { '<x val 1>': '<y val 1>', '<x val 2>': '<y val 2>' },
'sample 2': { '<x val 1>': '<y val 1>', '<x val 2>': '<y val 2>' }
}
]
```
You'll also want to add the following configuration options to
give names to the buttons and graph labels:
```python
config = {
'data_labels': [
{'name': 'DS 1', 'ylab': 'Dataset 1', 'xlab': 'x Axis 1'},
{'name': 'DS 2', 'ylab': 'Dataset 2', 'xlab': 'x Axis 2'}
]
}
```
All of these config values are optional, the function will default
to sensible values if things are missing.
### Additional data series
Sometimes, it's good to be able to specify specific data series manually.
To do this, use `config['extra_series']`. For a single extra line this can
be a dict (as below). For multiple lines, use a list of dicts. For multiple
dataset plots, use a list of list of dicts.
For example, to add a dotted `x = y` reference line:
```python
from multiqc.plots import linegraph
config = {
'extra_series': {
'name': 'x = y',
'data': [[0, 0], [max_x_val, max_y_val]],
'dashStyle': 'Dash',
'lineWidth': 1,
'color': '#000000',
'marker': { 'enabled': False },
'enableMouseTracking': False,
'showInLegend': False,
}
}
html_content = linegraph.plot(data, config)
```
## Scatter Plots
Scatter plots work in almost exactly the same way as line plots. Most (if not all)
config options are shared between the two. The data structure is similar but not identical:
```python
from multiqc.plots import scatter
data = {
'sample 1': {
x: '<x val>',
y: '<y val>'
},
'sample 2': {
x: '<x val>',
y: '<y val>'
}
}
html_content = scatter.plot(data)
```
Note that you must use the keys `x` and `y` for each data point.
If you want more than one data point per sample, you can supply a list of
dictionaries instead. You can also optionally specify point colours and
sample name suffixes (these are appended to the sample name):
```python
data = {
'sample 1': [
{ x: '<x val>', y: '<y val>', color: '#a6cee3', name: 'Type 1' },
{ x: '<x val>', y: '<y val>', color: '#1f78b4', name: 'Type 2' }
],
'sample 2': [
{ x: '<x val>', y: '<y val>', color: '#b2df8a', name: 'Type 1' },
{ x: '<x val>', y: '<y val>', color: '#33a02c', name: 'Type 2' }
]
}
```
Remember that MultiQC reports can contain large numbers of samples, so this plot type
is **not** suitable for large quantities of data - 20,000 genes might look good
for one sample, but when someone runs MultiQC with 500 samples, it will crash
the browser and be impossible to interpret.
See the above docs about line plots for most config options. The scatter plot
has a handful of unique ones in addition:
```python
pconfig = {
'marker_colour': 'rgba(124, 181, 236, .5)', # string, base colour of points (recommend rgba / semi-transparent)
'marker_size': 5, # int, size of points
'marker_line_colour': '#999', # string, colour of point border
'marker_line_width': 1, # int, width of point border
'square': False # Force the plot to stay square? (Maintain aspect ratio)
}
```
## Creating a table
Tables should work just like the functions above (most like the bar
graph function). As a minimum, the function takes a dictionary containing
data - the first keys will be sample names (row headers) and each key
contained within will be a table column header.
You can also supply a list of key names to restrict the data in the table
to certain keys / columns. This also specifies the order that columns
should be displayed in.
For more customisation, the headers can be supplied as a dictionary. Each
key should match the keys used in the data dictionary, but values can
customise the output. If you want to specify the order of the columns, you
must use an `OrderedDict`.
Finally, the function accepts a config dictionary as a third parameter.
This can set global options for the table (eg. a title) and can also hold
default values to customise the output of all table columns.
The default header keys are:
```python
single_header = {
'namespace': '', # Name for grouping. Prepends desc and is in Config Columns modal
'title': '[ dict key ]', # Short title, table column title
'description': '[ dict key ]', # Longer description, goes in mouse hover text
'max': None, # Minimum value in range, for bar / colour coding
'min': None, # Maximum value in range, for bar / colour coding
'ceiling': None, # Maximum value for automatic bar limit
'floor': None, # Minimum value for automatic bar limit
'minRange': None, # Minimum range for automatic bar
'scale': 'GnBu', # Colour scale for colour coding. False to disable.
'bgcols': None, # Dict with values: background colours for categorical data.
'colour': '<auto>', # Colour for column grouping
'suffix': None, # Suffix for value (eg. '%')
'format': '{:,.1f}', # Value format string - default 1 decimal place
'cond_formatting_rules': None, # Rules for conditional formatting table cell values - see docs below
'cond_formatting_colours': None, # Styles for conditional formatting of table cell values
'shared_key': None # See below for description
'modify': None, # Lambda function to modify values
'hidden': False # Set to True to hide the column on page load
}
```
A third parameter can be specified with settings for the whole table:
```python
table_config = {
'namespace': '', # Name for grouping. Prepends desc and is in Config Columns modal
'id': '<random string>', # ID used for the table
'table_title': '<table id>', # Title of the table. Used in the column config modal
'save_file': False, # Whether to save the table data to a file
'raw_data_fn':'multiqc_<table_id>_table' # File basename to use for raw data file
'sortRows': True # Whether to sort rows alphabetically
'only_defined_headers': True # Only show columns that are defined in the headers config
'col1_header': 'Sample Name' # The header used for the first column
'no_beeswarm': False # Force a table to always be plotted (beeswarm by default if many rows)
}
```
Most of the header keys can also be specified in the table config
(`namespace`, `scale`, `format`, `colour`, `hidden`, `max`, `min`, `ceiling`, `floor`, `minRange`, `shared_key`, `modify`).
These will then be applied to all columns prior to applying column-specific heading config.
A very basic example of creating a table is shown below:
```python
data = {
'sample 1': {
'aligned': 23542,
'not_aligned': 343,
},
'sample 2': {
'aligned': 1275,
'not_aligned': 7328,
}
}
table_html = table.plot(data)
```
A more complicated version with ordered columns, defaults and column-specific
settings (eg. no decimal places):
```python
data = {
'sample 1': {
'aligned': 23542,
'not_aligned': 343,
'aligned_percent': 98.563952271
},
'sample 2': {
'aligned': 1275,
'not_aligned': 7328,
'aligned_percent': 14.820411484
}
}
headers = OrderedDict()
headers['aligned_percent'] = {
'title': '% Aligned',
'description': 'Percentage of reads that aligned',
'suffix': '%',
'max': 100,
'format': '{:,.0f}' # No decimal places please
}
headers['aligned'] = {
'title': '{} Aligned'.format(config.read_count_prefix),
'description': 'Aligned Reads ({})'.format(config.read_count_desc),
'shared_key': 'read_count',
'modify': lambda x: x * config.read_count_multiplier
}
config = {
'namespace': 'My Module',
'min': 0,
'scale': 'GnBu'
}
table_html = table.plot(data, headers, config)
```
### Table decimal places
You can customise how many decimal places a number has by using the `format` config
key for that column. The default format string is `'{:,.1f}'`, which specifies a
float number with a single decimal place. To remove decimals use `'{:,.0f}'`.
To have two decimal places, use `'{:,.2f}'`.
### Table colour scales
Colour scales are taken from [ColorBrewer2](http://colorbrewer2.org/).
Colour scales can be reversed by adding the suffix `-rev` to the name. For example, `RdYlGn-rev`.
The following scales are available:

### Custom cell background colours
You can specify custom background colours for specific values using the `bgcols`
header config. This takes precedence over `scale`.
For example, a header config for a column could look like this:
```python
headers[tablecol] = {
"title": "My table column",
"bgcols": {
"bad data": "#f8d7da",
"ok data": "#fff3cd",
"good data": "#d1e7dd"
}
}
```
### Zero centrepoints
If you set the header config `bars_zero_centrepoint` to `True`, the background bars
will use the absolute values to calculate bar width. So a value of `0` will have a bar
width of `0`, `20` a width of `20` and `-30` a width of `30`.
This works well with a divergent colour-scheme as the bar width shows the magnitude
of the value properly, whilst the colour scheme shows the difference between positive
and negative values.
For example:
```python
headers[tablecol] = {
"title": "My table column",
"scale": "RdYlGn",
"bars_zero_centrepoint": True,
}
```
### Conditional formatting of data values
MultiQC has configuration options to allow users to configure _"conditional formatting"_,
with highlighted values in table cells ([see docs](#conditional-formatting)).
Developers can also make use of this functionality within the header config dictionaries
for formatting data values.
The functionality follows the same logic as for user configs with the parameters
`cond_formatting_rules` and `cond_formatting_colours`. These correspond to the
user config options `table_cond_formatting_rules` and `table_cond_formatting_colours`,
with the exception that no column ID is needed for `table_cond_formatting_rules`.
For example, a simple header config could look as follows:
```python
headers[instrument] = {
"title": "My table column",
"cond_formatting_rules": {
"pass": [{"s_eq": "good data"}],
"warn": [{"s_eq": "ok data"}],
"fail": [{"s_eq": "bad data"}],
}
}
```
A more complex version with multiple rules could be:
```python
headers[tablecol] = {
"title": "My table column",
"cond_formatting_rules": {
"brightgreen": [
{"s_contains": "amazing"},
{"s_contains": "incredible"},
],
"brown": [{"s_ne": "rubbish-data"}],
"turquoise": [
{"gt": 4},
{"lt": 12},
],
},
"cond_formatting_colours": [
{"brightgreen": "#39FF14"},
{"brown": "#A52A2A"},
{"turquoise": "#30D5C8"},
]
}
```
## Beeswarm plots (dot plots)
Beeswarm plots work from the exact same data structure as tables, so the
usage is just the same. Except instead of calling `table`, call `beeswarm`:
```python
data = {
'sample 1': {
'aligned': 23542,
'not_aligned': 343,
},
'sample 2': {
'not_aligned': 7328,
'aligned': 1275,
}
}
beeswarm_html = beeswarm.plot(data)
```
The function also accepts the same headers and config parameters.
## Heatmaps
Heatmaps expect data in the structure of a list of lists. Then, a list
of sample names for the x-axis, and optionally for the y-axis (defaults
to the same as the x-axis).
```python
heatmap.plot(data, xcats, ycats, pconfig)
```
A simple example:
```python
hmdata = [
[0.9, 0.87, 0.73, 0.6, 0.2, 0.3],
[0.87, 1, 0.7, 0.6, 0.9, 0.3],
[0.73, 0.8, 1, 0.6, 0.9, 0.3],
[0.6, 0.8, 0.7, 1, 0.9, 0.3],
[0.2, 0.8, 0.7, 0.6, 1, 0.3],
[0.3, 0.8, 0.7, 0.6, 0.9, 1],
]
names = [ 'one', 'two', 'three', 'four', 'five', 'six' ]
hm_html = heatmap.plot(hmdata, names)
```
Much like the other plots, you can change the way that the heatmap looks
using a config dictionary:
```python
pconfig = {
'title': None, # Plot title - should be in format "Module Name: Plot Title"
'xTitle': None, # X-axis title
'yTitle': None, # Y-axis title
'min': None, # Minimum value (default: auto)
'max': None, # Maximum value (default: auto)
'square': True, # Force the plot to stay square? (Maintain aspect ratio)
'xcats_samples': True, # Is the x-axis sample names? Set to False to prevent report toolbox from affecting.
'ycats_samples': True, # Is the y-axis sample names? Set to False to prevent report toolbox from affecting.
'colstops': [] # Scale colour stops. See below.
'reverseColors': False, # Reverse the order of the colour axis
'decimalPlaces': 2, # Number of decimal places for tooltip
'legend': True, # Colour axis key enabled or not
'borderWidth': 0, # Border width between cells
'datalabels': True, # Show values in each cell. Defaults True when less than 20 samples.
'datalabel_colour': '<auto>', # Colour of text for values. Defaults to auto contrast.
'height': 512 # The default height of the interactive plot, in pixels
}
```
The colour stops are a bit special and can be used to define a custom colour
scheme. These should be defined as a list of lists, with a number between 0 and 1
and a HTML colour. The default is `RdYlBu` from [ColorBrewer](http://colorbrewer2.org/):
```python
pconfig = {
'colstops' = [
[0, '#313695'],
[0.1, '#4575b4'],
[0.2, '#74add1'],
[0.3, '#abd9e9'],
[0.4, '#e0f3f8'],
[0.5, '#ffffbf'],
[0.6, '#fee090'],
[0.7, '#fdae61'],
[0.8, '#f46d43'],
[0.9, '#d73027'],
[1, '#a50026'],
]
}
```
## Javascript Functions
The javascript bundled in the default MultiQC template has a number of
helper functions to make your life easier.
> NB: The MultiQC Python functions make use of these, so it's very unlikely
> that you'll need to use any of this. But it's here for reference.
### Plotting line graphs
`plot_xy_line_graph (target, ds)`
Plots a line graph with multiple series of (x,y) data pairs. Used by
the [linegraph.plot()](http://multiqc.info/docs/#line-graphs)
python function.
Data and configuration must be added to the document level
`mqc_plots` variable on page load, using the target as the key.
The variables used are as follows:
```javascript
mqc_plots[target]["plot_type"] = "xy_line";
mqc_plots[target]["config"];
mqc_plots[target]["datasets"];
```
Multiple datasets can be added in the `['datasets']` array. The supplied
variable `ds` specifies which is plotted (defaults to `0`).
Available config options with default vars:
```javascript
config = {
title: undefined, // Plot title
xlab: undefined, // X axis label
ylab: undefined, // Y axis label
xCeiling: undefined, // Maximum value for automatic axis limit (good for percentages)
xFloor: undefined, // Minimum value for automatic axis limit
xMinRange: undefined, // Minimum range for axis
xmax: undefined, // Max x limit
xmin: undefined, // Min x limit
xDecimals: true, // Set to false to only show integer labels
yCeiling: undefined, // Maximum value for automatic axis limit (good for percentages)
yFloor: undefined, // Minimum value for automatic axis limit
yMinRange: undefined, // Minimum range for axis
ymax: undefined, // Max y limit
ymin: undefined, // Min y limit
yDecimals: true, // Set to false to only show integer labels
yPlotBands: undefined, // Highlighted background bands. See http://api.highcharts.com/highcharts#yAxis.plotBands
xPlotBands: undefined, // Highlighted background bands. See http://api.highcharts.com/highcharts#xAxis.plotBands
tt_label: "{point.x}: {point.y:.2f}", // Use to customise tooltip label, eg. '{point.x} base pairs'
pointFormat: undefined, // Replace the default HTML for the entire tooltip label
click_func: function () {}, // Javascript function to be called when a point is clicked
cursor: undefined, // CSS mouse cursor type. Defaults to pointer when 'click_func' specified
};
```
An example of the markup expected, with the function being called:
```html
<div id="my_awesome_line_graph" class="hc-plot"></div>
<script type="text/javascript">
mqc_plots["#my_awesome_bar_plot"]["plot_type"] = "xy_line";
mqc_plots["#my_awesome_line_graph"]["datasets"] = [
{
name: "Sample 1",
data: [
[1, 1.5],
[1.5, 3.1],
[2, 6.4],
],
},
{
name: "Sample 2",
data: [
[1, 1.7],
[1.5, 4.3],
[2, 8.4],
],
},
];
mqc_plots["#my_awesome_line_graph"]["config"] = {
title: "Best Plot Ever",
ylab: "Pings",
xlab: "Pongs",
};
$(function () {
plot_xy_line_graph("#my_awesome_line_graph");
});
</script>
```
### Plotting bar graphs
`plot_stacked_bar_graph (target, ds)`
Plots a bar graph with multiple series containing multiple categories.
Used by the [bargraph.plot()](http://multiqc.info/docs/#bar-graphs)
python function.
Data and configuration must be added to the document level
`mqc_plots` variable on page load, using the target as the key.
The variables used are as follows:
```javascript
mqc_plots[target]["plot_type"] = "bar_graph";
mqc_plots[target]["config"];
mqc_plots[target]["datasets"];
mqc_plots[target]["samples"];
```
All available config options with default vars:
```javascript
config = {
title: undefined, // Plot title
xlab: undefined, // X axis label
ylab: undefined, // Y axis label
ymax: undefined, // Max y limit
ymin: undefined, // Min y limit
yDecimals: true, // Set to false to only show integer labels
ylab_format: undefined, // Format string for x axis labels. Defaults to {value}
stacking: "normal", // Set to null to have category bars side by side (None in python)
xtype: "linear", // Axis type. 'linear' or 'logarithmic'
use_legend: true, // Show / hide the legend
click_func: undefined, // Javascript function to be called when a point is clicked
cursor: undefined, // CSS mouse cursor type. Defaults to pointer when 'click_func' specified
tt_percentages: true, // Show the percentages of each count in the tooltip
reversedStacks: false, // Reverse the order of the categories in the stack.
};
```
An example of the markup expected, with the function being called:
```html
<div id="my_awesome_bar_plot" class="hc-plot"></div>
<script type="text/javascript">
mqc_plots["#my_awesome_bar_plot"]["plot_type"] = "bar_graph";
mqc_plots["#my_awesome_bar_plot"]["samples"] = ["Sample 1", "Sample 2"];
mqc_plots["#my_awesome_bar_plot"]["datasets"] = [
{ data: [4, 7], name: "Passed Test" },
{ data: [2, 3], name: "Failed Test" },
];
mqc_plots["#my_awesome_bar_plot"]["config"] = {
title: "My Awesome Plot",
ylab: "# Observations",
ymin: 0,
stacking: "normal",
};
$(function () {
plot_stacked_bar_graph("#my_awesome_bar_plot");
});
</script>
```
### Switching counts and percentages
If you're using the plotting functions above, it's easy to add a button which
switches between percentages and counts. Just add the following HTML above
your plot:
```html
<div class="btn-group switch_group">
<button class="btn btn-default btn-sm active" data-action="set_numbers" data-target="#my_plot">Counts</button>
<button class="btn btn-default btn-sm" data-action="set_percent" data-target="#my_plot">Percentages</button>
</div>
```
_NB:_ This markup is generated automatically with the Python `self.plot_bargraph()` function.
### Switching plot datasets
Much like the counts / percentages buttons above, you can add a button which
switches the data displayed in a single plot. Make sure that both datasets
are stored in named javascript variables, then add the following markup:
```html
<div class="btn-group switch_group">
<button
class="btn btn-default btn-sm active"
data-action="set_data"
data-ylab="First Data"
data-newdata="data_var_1"
data-target="#my_plot"
>
Data 1
</button>
<button
class="btn btn-default btn-sm"
data-action="set_data"
data-ylab="Second Data"
data-newdata="data_var_2"
data-target="#my_plot"
>
Data 2
</button>
</div>
```
Note the CSS class `active` which specifies which button is 'pressed' on page load.
`data-ylab` and `data-xlab` can be used to specify the new axes labels.
`data-newdata` should be the name of the javascript object with the new data
to be plotted and `data-target` should be the CSS selector of the plot to change.
### Custom event triggers
Some of the events that take place in the general javascript
code trigger jQuery events which you can hook into from within your
module's code. This allows you to take advantage of events generated
by the global theme whilst keeping your code modular.
```javascript
$(document).on("mqc_highlights", function (e, f_texts, f_cols, regex_mode) {
// This trigger is called when the highlight strings are
// updated. Three variables are given - an array of search
// strings (f_texts), an array of colours with corresponding
// indexes (f_cols) and a boolean var saying whether the
// search should be treated as a string or a regex (regex_mode)
});
$(document).on("mqc_renamesamples", function (e, f_texts, t_texts, regex_mode) {
// This trigger is called when samples are renamed
// Three variables are given - an array of search
// strings (f_texts), an array of replacements with corresponding
// indexes (t_texts) and a boolean var saying whether the
// search should be treated as a string or a regex (regex_mode)
});
$(document).on("mqc_hidesamples", function (e, f_texts, regex_mode) {
// This trigger is called when the Hide Samples filters change.
// Two variables are given - an array of search strings
// (f_texts) and a boolean saying whether the search should
// be treated as a string or a regex (regex_mode)
});
$("#YOUR_PLOT_ID").on("mqc_plotresize", function () {
// This trigger is called when a plot handle is pulled,
// resizing the height
});
$("#YOUR_PLOT_ID").on("mqc_original_series_click", function (e, name) {
// A plot able to show original images has had a point clicked.
// 'name' contains the name of the series that was clicked
});
$("#YOUR_PLOT_ID").on("mqc_original_chg_source", function (e, name) {
// A plot with original images has had a request to change the
// original image source (eg. pressing Prev / Next)
});
$("#YOUR_PLOT_ID").on("mqc_plotexport_image", function (e, cfg) {
// A trigger to export an image of the plot. cfg contains
// config variables for the requested image.
});
$("#YOUR_PLOT_ID").on("mqc_plotexport_data", function (e, cfg) {
// A trigger to export a data file of the plot. cfg contains
// config variables for the requested data.
});
```
|