import matplotlib.pyplot as plt
import seaborn as sns
# Just import maidr package
import maidr
# Load the penguins dataset
= sns.load_dataset("penguins")
penguins
# Create a bar plot showing the average body mass of penguins by species
=(6, 6))
plt.figure(figsize
# Assign the plot to a variable
= sns.barplot(
bar_plot ="species", y="body_mass_g", data=penguins, errorbar="sd", palette="Blues_d"
x
)"Average Body Mass of Penguins by Species")
plt.title("Species")
plt.xlabel("Body Mass (g)")
plt.ylabel(
# plt.show()
# Use maidr.show() to display your plot
maidr.show(bar_plot)
Example Gallery
Example Gallery
Making accessible data representation with maidr is easy and straightforward. If you already have data visualization code using matplotlib or seaborn, you can make your plots accessible with maidr in just a few lines of code.
Simply import the maidr
package and use the maidr.show()
function to display your plots. maidr will automatically generate accessible versions of your plots in your default browser. You can then interact with the accessible versions using keyboard shortcuts (refer to Table 1).
Bar Plots
Simple Bar Plot
Vertical Stacked Bar Plot
import matplotlib.pyplot as plt
import numpy as np
import maidr
= (
species "Adelie\nMean = 3700.66g",
"Chinstrap\nMean = 3733.09g",
"Gentoo\nMean = 5076.02g",
)= {
weight_counts "Below": np.array([70, 31, 58]),
"Above": np.array([82, 37, 66]),
}= 0.5
width
= plt.subplots()
fig, ax
= np.zeros(3)
bottom
for boolean, weight_count in weight_counts.items():
= ax.bar(species, weight_count, width, label=boolean, bottom=bottom)
p += weight_count
bottom
"Species of Penguins")
ax.set_xlabel("Average Body Mass")
ax.set_ylabel(
"Number of penguins with above average body mass")
ax.set_title(="upper right")
ax.legend(loc
maidr.show(p)
Side-By-Side Dodged Bar Plot
import matplotlib.pyplot as plt
import numpy as np
import maidr
tuple[str, str, str] = (
species: "Adelie\n $\\mu=3700.66g$",
"Chinstrap\n $\\mu=3733.09g$",
"Gentoo\n $\\mu=5076.02g$",
)dict[str, np.ndarray] = {
weight_counts: "Below": np.array([70, 31, 58]),
"Above": np.array([82, 37, 66]),
}
= np.arange(len(species))
x: np.ndarray int = len(weight_counts)
total_groups: float = 0.35
width:
= plt.subplots()
fig, ax
list[float] = [(-width / 2) + i * width for i in range(total_groups)]
offsets:
for offset, (category, counts) in zip(offsets, weight_counts.items()):
= x + offset
positions = ax.bar(positions, counts, width, label=category)
p
# Set x-axis labels and title
ax.set_xticks(x)
ax.set_xticklabels(species)"Species")
ax.set_xlabel("Dodged Bar Plot: Penguin Weight Counts")
ax.set_title(="upper right")
ax.legend(loc
# Show plot using maidr.show
maidr.show(p)
Histogram
import matplotlib.pyplot as plt
import seaborn as sns
import maidr
# Load the Iris dataset
= sns.load_dataset("iris")
iris
# Select the petal lengths
= iris["petal_length"]
petal_lengths
# Plot a histogram of the petal lengths
=(6, 6))
plt.figure(figsize
= sns.histplot(petal_lengths, kde=True, color="blue", binwidth=0.5)
hist_plot
"Petal Lengths in Iris Dataset")
plt.title("Petal Length (cm)")
plt.xlabel("Frequency")
plt.ylabel(
# plt.show()
maidr.show(hist_plot)
Line Plots
Single Line Plot
import matplotlib.pyplot as plt
import seaborn as sns
import maidr
# Load the 'tips' dataset from seaborn
= sns.load_dataset("tips")
tips
# Choose a specific subset of the dataset (e.g., data for 'Thursday')
= tips[tips["day"] == "Thur"]
subset_data
# Create a line plot
=(6, 6))
plt.figure(figsize= sns.lineplot(
line_plot =subset_data,
data="total_bill",
x="tip",
y=True,
markers="day",
style=False,
legend
)"Tips vs Total Bill (Thursday)")
plt.title("Total Bill")
plt.xlabel("Tip")
plt.ylabel(
# plt.show()
maidr.show(line_plot)
Multiline Plot
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import maidr
# Create sample data points
= np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.array([2, 4, 1, 5, 3, 7, 6, 8])
y1 = np.array([1, 3, 5, 2, 4, 6, 8, 7])
y2 = np.array([3, 1, 4, 6, 5, 2, 4, 5])
y3
# Convert to pandas DataFrame for seaborn
= pd.DataFrame(
data
{"x": np.tile(x, 3),
"y": np.concatenate([y1, y2, y3]),
"series": np.repeat(["Series 1", "Series 2", "Series 3"], len(x)),
}
)
# Create the plot
=(6, 6))
plt.figure(figsize
# Use seaborn lineplot for multiple lines
= sns.lineplot(
lineplot ="x", y="y", hue="series", style="series", markers=True, dashes=True, data=data
x
)
# Customize the plot
"Seaborn Multiline Plot")
plt.title("X values")
plt.xlabel("Y values")
plt.ylabel(
# Display the plot using maidr
maidr.show(lineplot)
Heat Map
import matplotlib.pyplot as plt
import seaborn as sns
import maidr
# Load an example dataset from seaborn
= sns.load_dataset("glue").pivot(index="Model", columns="Task", values="Score")
glue
# Plot a heatmap
=(8, 8))
plt.figure(figsize= sns.heatmap(glue, annot=True, fill_label="Score")
heatmap "Model Scores by Task")
plt.title(
# Show the plot
# plt.show()
maidr.show(heatmap)
Box Plot
- Note: Visual highlight feature has not been implemented in the box plot yet.
import matplotlib.pyplot as plt
import seaborn as sns
from seaborn import load_dataset
import maidr
# Load the iris dataset
= load_dataset("iris")
iris
# Create the horizontal boxplot
= sns.boxplot(x="petal_length", y="species", data=iris, orient="h")
horz_box_plot "Species")
plt.ylabel("Petal Length")
plt.xlabel("Petal Length by Species from Iris Dataset")
plt.title(# plt.show()
# Show the plot
maidr.show(horz_box_plot)
Scatter Plot
import matplotlib.pyplot as plt
import seaborn as sns
import maidr
# Create a scatter plot
= sns.scatterplot(
scatter_plot =iris, x="sepal_length", y="sepal_width", hue="species"
data
)
# Adding title and labels (optional)
"Iris Sepal Length vs Sepal Width")
plt.title("Sepal Length")
plt.xlabel("Sepal Width")
plt.ylabel(
# Show the plot
# plt.show()
maidr.show(scatter_plot)
Multi-Layered Plots
import matplotlib.pyplot as plt
import numpy as np
import maidr
# Generate sample data
= np.arange(5)
x = np.array([3, 5, 2, 7, 3])
bar_data = np.array([10, 8, 12, 14, 9])
line_data
# Create a figure and a set of subplots
= plt.subplots(figsize=(8, 5))
fig, ax1
# Create the bar chart on the first y-axis
="skyblue", label="Bar Data")
ax1.bar(x, bar_data, color"X values")
ax1.set_xlabel("Bar values", color="blue")
ax1.set_ylabel(="y", labelcolor="blue")
ax1.tick_params(axis
# Create a second y-axis sharing the same x-axis
= ax1.twinx()
ax2
# Create the line chart on the second y-axis
="red", marker="o", linestyle="-", label="Line Data")
ax2.plot(x, line_data, color"X values")
ax2.set_xlabel("Line values", color="red")
ax2.set_ylabel(="y", labelcolor="red")
ax2.tick_params(axis
# Add title and legend
"Multilayer Plot Example")
plt.title(
# Add legends for both axes
= ax1.get_legend_handles_labels()
lines1, labels1 = ax2.get_legend_handles_labels()
lines2, labels2 + lines2, labels1 + labels2, loc="upper left")
ax1.legend(lines1
# Adjust layout
fig.tight_layout()
maidr.show(fig)
Multi-Panel Plots (Multiple Subplots)
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import maidr
# Set the plotting style
="whitegrid")
sns.set_theme(style
# Data for line plot
= np.array([1, 2, 3, 4, 5, 6, 7, 8])
x_line = np.array([2, 4, 1, 5, 3, 7, 6, 8])
y_line = {"x": x_line, "y": y_line}
line_data
# Data for first bar plot
= ["A", "B", "C", "D", "E"]
categories = np.random.rand(5) * 10
values = {"categories": categories, "values": values}
bar_data
# Data for second bar plot
= ["A", "B", "C", "D", "E"]
categories_2 = np.random.randn(5) * 100
values_2 = {"categories": categories_2, "values": values_2}
bar_data_2
# Create a figure with 3 subplots arranged vertically
= plt.subplots(3, 1, figsize=(6, 12))
fig, axs
# First panel: Line plot using seaborn
="x", y="y", data=line_data, color="blue", linewidth=2, ax=axs[0])
sns.lineplot(x0].set_title("Line Plot: Random Data")
axs[0].set_xlabel("X-axis")
axs[0].set_ylabel("Values")
axs[
# Second panel: Bar plot using seaborn
sns.barplot(="categories", y="values", data=bar_data, color="green", alpha=0.7, ax=axs[1]
x
)1].set_title("Bar Plot: Random Values")
axs[1].set_xlabel("Categories")
axs[1].set_ylabel("Values")
axs[
# Third panel: Bar plot using seaborn
sns.barplot(="categories", y="values", data=bar_data_2, color="blue", alpha=0.7, ax=axs[2]
x
)2].set_title("Bar Plot 2: Random Values") # Fixed the typo in the title
axs[2].set_xlabel("Categories")
axs[2].set_ylabel("Values")
axs[
# Adjust layout to prevent overlap
plt.tight_layout()
# Display the figure
maidr.show(fig)
Facet Plot
import matplotlib.pyplot as plt
import numpy as np
import maidr
= ["A", "B", "C", "D", "E"]
categories
42)
np.random.seed(= np.random.rand(5) * 10
data_group1 = np.random.rand(5) * 100
data_group2 = np.random.rand(5) * 36
data_group3 = np.random.rand(5) * 42
data_group4
= [data_group1, data_group2, data_group3, data_group4]
data_sets = ["Group 1", "Group 2", "Group 3", "Group 4"]
condition_names
= plt.subplots(2, 2, figsize=(7, 7), sharey=True, sharex=True)
fig, axs = axs.flatten()
axs
= np.concatenate(data_sets)
all_data = np.min(all_data) * 0.9, np.max(all_data) * 1.1
y_min, y_max
# Create a bar plot in each subplot
for i, (data, condition) in enumerate(zip(data_sets, condition_names)):
=f"C{i}", alpha=0.7)
axs[i].bar(categories, data, colorf"{condition}")
axs[i].set_title(# Set consistent y-axis limits
axs[i].set_ylim(y_min, y_max)
# Add value labels on top of each bar
for j, value in enumerate(data):
axs[i].text(
j,+ (y_max - y_min) * 0.02,
value f"{value:.1f}",
="center",
ha="bottom",
va=9,
fontsize
)
# Add common labels
0.5, 0.04, "Categories", ha="center", va="center", fontsize=14)
fig.text(
fig.text(0.06, 0.5, "Values", ha="center", va="center", rotation="vertical", fontsize=14
)
# Add a common title
"Facet Plot: Bar Charts by Condition", fontsize=16)
fig.suptitle(
# Adjust layout
=(0.08, 0.08, 0.98, 0.95))
plt.tight_layout(rect
maidr.show(fig)
Reactive Dashboard
Shiny
Check out a reactive Shiny dashboard example with maidr and its source code is available on GitHub.
Streamlit
Check out this Streamlit dashboard with maidr, and its source code is available on GitHub.
* Note: `Streamlit` framework has some "Unlabeled 0 Button" which does not have to do with our maidr package. This issue needs to be addressed by the `Streamlit` team.
Interactive Computing (Jupyter Notebooks, Jupyter Labs, Google Colab)
Check out this interactive notebook in Google Colab.
Other Examples
We provide some example code for using py-maidr with matplotlib, seaborn, Jupyter Notebook, Quarto, Shiny, and Streamlit.
Keyboard Shortcuts and Controls
To interact with the plots using maidr, follow these steps:
- Press the Tab key to focus on the plot element.
- Use the arrow keys to move around the plot.
- Press B to toggle Braille mode.
- Press T to toggle Text mode.
- Press S to toggle Sonification (tones) mode.
- Press R to toggle Review mode.
Below is a detailed list of keyboard shortcuts for various functions:
Function | Windows and Linux Key | Mac Key |
---|---|---|
Toggle Braille Mode | b | b |
Toggle Text Mode | t | t |
Toggle Sonification Mode | s | s |
Toggle Review Mode | r | r |
Move around plot | Arrow keys | Arrow keys |
Go to the very left right up down | Ctrl + Arrow key | CMD + Arrow key |
Select the first element | Ctrl + Home | CMD + Home |
Select the last element | Ctrl + End | CMD + End |
Repeat current sound | Space | Space |
Auto-play outward in direction of arrow | Ctrl + Shift + Arrow key | CMD + Shift + Arrow key |
Stop Auto-play | Ctrl | Ctrl |
Auto-play speed up | Period (.) | Period (.) |
Auto-play speed down | Comma (,) | Comma (,) |
Auto-play speed reset | Slash (/) | Slash (/) |
Check label for the title of current plot | l t | l t |
Check label for the x axis of current plot | l x | l x |
Check label for the y axis of current plot | l y | l y |
Check label for the fill (z) axis of current plot | l f | l f |
Switch to next layer | PageUp | PageUp |
Switch to previous layer | PageDown | PageDown |
Move around subplot list | Arrow keys | Arrow keys |
Activate selected subplot in the list | Enter | Enter |
Escape from current subplot to return to the subplot list | ESC | ESC |
Open settings | Ctrl + comma (,) | CMD + comma (,) |
Open Chat View | Question (?) | Question (?) |
Open keyboard help | Ctrl + Slash (/) | CMD + Slash (/) |
Demo Video
Bug Report
If you encounter a bug, have usage questions, or want to share ideas to make this package better, please feel free to file an issue.
Code of Conduct
Please note that the maidr project is released with a contributor code of conduct.
By participating in this project you agree to abide by its terms.
📄 License
maidr is licensed under the GPL3 license.
🏛️ Governance
This project is primarily maintained by JooYoung Seo and Saairam Venkatesh. Other authors may occasionally assist with some of these duties.