Skip to content

Improve violin plot demo #7251

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

Closed
3 tasks done
tacaswell opened this issue Oct 11, 2016 · 8 comments
Closed
3 tasks done

Improve violin plot demo #7251

tacaswell opened this issue Oct 11, 2016 · 8 comments
Labels
Difficulty: Easy https://matplotlib.org/devdocs/devel/contribute.html#good-first-issues Documentation
Milestone

Comments

@tacaswell
Copy link
Member

tacaswell commented Oct 11, 2016

#6814 has a number of outstanding comments to clarify and generalize the example code that the OP declined to make.

http://matplotlib.org/devdocs/examples/statistics/customized_violin_demo.html

Here is a list of elements to do:

  • use numpy function instead of writing our own
  • write helper function to deal with the repetitive axes manipulation
  • Add a docstring sphinx-gallery compatible with a title and a description of the example.

[edited to fix link]
[edited to add the todo list]

@tacaswell tacaswell added this to the 2.0.1 (next bug fix release) milestone Oct 11, 2016
@afvincent
Copy link
Contributor

@tacaswell
Copy link
Member Author

To be more specific:

  • use numpy function instead of writing our own
  • write helper function to deal with the repetitive axes manipulation

@NelleV NelleV added the Difficulty: Easy https://matplotlib.org/devdocs/devel/contribute.html#good-first-issues label Oct 11, 2016
@nalshihabi
Copy link
Contributor

Hello, I am new here and I would like to contribute. I will begin working on this and fix what is asked for.

@DrNightmare
Copy link
Contributor

Hi, I worked on this a bit and got the following done:
From @story645 's code and the general comments in #6814:

  1. Replaced the defined percentile function with a call to np.percentile
  2. Used np.clip as suggested
  3. Used list comprehensions, this is more pythonic and more readable

Minor changes:
4. Moved the styling of axes to a function
5. Rearranged overall code, made some code more pythonic, renamed certain variables, added short comments to make the example more readable

Could someone review this?

"""
=================================
Demo of violin plot customization
=================================

This example demonstrates how to fully customize violin plots.
The first plot shows the default style by providing only
the data. The second plot first limits what matplotlib draws
with additional kwargs. Then a simplified representation of
a box plot is drawn on top. Lastly, the styles of the artists
of the violins are modified.

For more information on violin plots, the scikit-learn docs have a great
section: http://scikit-learn.org/stable/modules/density.html
"""

import matplotlib.pyplot as plt
import numpy as np


def adjacent_values(vals):
    q1, q3 = np.percentile(vals, [25, 75])
    # inter-quartile range iqr
    iqr = q3 - q1
    # upper adjacent values
    uav = q3 + iqr * 1.5
    uav = np.clip(uav, q3, vals[-1])
    # lower adjacent values
    lav = q1 - iqr * 1.5
    lav = np.clip(lav, q1, vals[0])
    return [lav, uav]


def set_axis_style(ax, labels):
    ax.get_xaxis().set_tick_params(direction='out')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks(np.arange(1, len(labels) + 1))
    ax.set_xticklabels(labels)
    ax.set_xlim(0.25, len(labels) + 0.75)
    ax.set_xlabel('Sample name')


# create test data
np.random.seed(123)
dat = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 4), sharey=True)

# plot the default violin
ax1.set_title('Default violin plot')
ax1.set_ylabel('Observed values')
ax1.violinplot(dat)

# customized violin
ax2.set_title('Customized violin plot')
parts = ax2.violinplot(
        dat, showmeans=False, showmedians=False,
        showextrema=False)

# customize colors
for pc in parts['bodies']:
    pc.set_facecolor('#D43F3A')
    pc.set_edgecolor('black')
    pc.set_alpha(1)

# medians
med = [np.percentile(sarr, 50) for sarr in dat]
# inter-quartile ranges
iqr = [[np.percentile(sarr, 25), np.percentile(sarr, 75)] for sarr in dat]
# upper and lower adjacent values
avs = [adjacent_values(sarr) for sarr in dat]

# plot whiskers as thin lines, quartiles as fat lines,
# and medians as points
for i, median in enumerate(med):
    # whiskers
    ax2.plot([i + 1, i + 1], avs[i], '-', color='black', linewidth=1)
    # quartiles
    ax2.plot([i + 1, i + 1], iqr[i], '-', color='black', linewidth=5)
    # medians
    ax2.plot(
        i + 1, median, 'o', color='white',
        markersize=6, markeredgecolor='none')

# set style for the axes
labels = ['A', 'B', 'C', 'D']    # labels
for ax in [ax1, ax2]:
    set_axis_style(ax, labels)

plt.subplots_adjust(bottom=0.15, wspace=0.05)
plt.show()

@tacaswell
Copy link
Member Author

@DrNightmare Can you please commit those changes and open a pull request with them?

See http://matplotlib.org/devdocs/devel/gitwash/development_workflow.html

@tacaswell
Copy link
Member Author

@NoahShihabi @DrNightmare Can you two please coordinate on this?

@DrNightmare
Copy link
Contributor

@tacaswell Sure, I'll open the PR

DrNightmare added a commit to DrNightmare/matplotlib that referenced this issue Oct 29, 2016
phobson added a commit that referenced this issue Oct 31, 2016
Updated violin plot example as per suggestions in issue #7251
phobson added a commit that referenced this issue Oct 31, 2016
Updated violin plot example as per suggestions in issue #7251
@phobson
Copy link
Member

phobson commented Oct 31, 2016

closed via #7360

@phobson phobson closed this as completed Oct 31, 2016
bcongdon pushed a commit to bcongdon/matplotlib that referenced this issue Nov 8, 2016
bcongdon pushed a commit to bcongdon/matplotlib that referenced this issue Nov 8, 2016
@QuLogic QuLogic modified the milestones: 2.0 (style change major release), 2.0.1 (next bug fix release) Dec 7, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Difficulty: Easy https://matplotlib.org/devdocs/devel/contribute.html#good-first-issues Documentation
Projects
None yet
Development

No branches or pull requests

7 participants