-
Notifications
You must be signed in to change notification settings - Fork 7
Blog - bar #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kdorr
wants to merge
3
commits into
matplotlib:gh-pages
Choose a base branch
from
kdorr:blog-bar
base: gh-pages
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Blog - bar #25
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
--- | ||
layout: post | ||
title: "Making a Bar Chart" | ||
date: 2018-08-15 16:00:00 -0500 | ||
author: "Kimberly Orr and Nabarun Pal" | ||
categories: user-guide | ||
tags: "intro about bar" | ||
excerpt_separator: <!--read more--> | ||
--- | ||
|
||
# Making a Bar Chart | ||
At the time of writing, mpl-altair does not support bar charts, so this post will show how to create a bar chart in Altair, Matplotlib, and how mpl-altair _should_ implement bar chart conversion in the future. | ||
|
||
We'll work with the following long-form DataFrame for this example: | ||
```python | ||
import pandas as pd | ||
df = pd.DataFrame({ | ||
'group': ['1', '1', '2', '2', '3', '3', '4', '4', '5', '5'], | ||
'variable': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'], | ||
'scores': [20, 25, 35, 32, 30, 34, 35, 20, 27, 25] | ||
}) | ||
``` | ||
|
||
## Altair | ||
For this dataset, specifying the color will automatically stack the bar charts. | ||
```python | ||
import altair as alt | ||
alt.Chart(df).mark_bar().encode( | ||
x='group', | ||
y='scores', | ||
color='variable' | ||
) | ||
``` | ||
 | ||
|
||
## Matplotlib | ||
This is a little more complicated in Matplotlib. Since Matplotlib is procedural, we have to manually tell Matplotlib to stack the bars. Also notice that we are calling a new function now (`ax.bar()`) to get a bar plot. | ||
|
||
To stack the bars, we have to create new subset dataframes and then plot each one separately (specifying that bottom of one plot should be the top of another `bottom=a_scores`). One way to do this is to subset via indexing (option 1). Another way to do this is to use the `df.groupby()` function (option 2). | ||
```python | ||
import matplotlib.pyplot as plt | ||
``` | ||
```python | ||
# Option 1 | ||
fig, ax = plt.subplots() | ||
groups = df['group'].unique() | ||
a_scores = df[df['variable']=='a']['scores'] | ||
b_scores = df[df['variable']=='b']['scores'] | ||
ax.bar(groups, a_scores, label='a') | ||
ax.bar(groups, b_scores, bottom=a_scores, label='b') | ||
ax.set_xlabel('groups') | ||
ax.set_ylabel('scores') | ||
ax.legend() | ||
plt.grid() | ||
plt.show() | ||
``` | ||
```python | ||
# Option 2 | ||
fig, ax = plt.subplots() | ||
|
||
(_, a), (_, b) = df.groupby('variable') | ||
ax.bar(a['group'], a['scores'], label='a') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This might be clearer as bottom = np.zeros(len(a['group'])
for label, scores in df.groupby('variable');
ax.bar(scoren['group'], scores['scores'], bottom=bottom, label=label)
bottom += scores['scores'] |
||
ax.bar(b['group'], b['scores'], bottom=a['scores'], label='b') | ||
ax.set_xlabel('groups') | ||
ax.set_ylabel('scores') | ||
ax.legend() | ||
plt.grid() | ||
plt.show() | ||
``` | ||
Both produce: | ||
|
||
 | ||
|
||
|
||
## mpl-altair | ||
At the time of writing, mpl-altair doesn't support bar charts. | ||
|
||
If mpl-altair supported bar charts, this is how an Altair chart would get rendered in mpl-altair: | ||
```python | ||
import altair as alt | ||
import matplotlib.pyplot as plt | ||
import mplaltair | ||
chart = alt.Chart(df).mark_bar().encode( | ||
x='group', | ||
y='scores', | ||
color='variable' | ||
) | ||
fig, ax = mplaltair.convert(chart) | ||
plt.show() | ||
``` |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Worried that this phrasing may be confusing since the bottom=a uses the top of a as the bottom of b. Maybe just state it explicitly? In this example, we first plot group a. Then we plot group b, using the bottom=a kwarg to plot b starting from the top of each a bar (and yes that can be phrased more cleanly too)