Skip to content

Instantly share code, notes, and snippets.

@cswiercz
Created March 23, 2020 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cswiercz/edcf294523ec4ba9ef008e980126ecd1 to your computer and use it in GitHub Desktop.
Save cswiercz/edcf294523ec4ba9ef008e980126ecd1 to your computer and use it in GitHub Desktop.
Example pandas plotting by label
import pandas as pd
import matplotlib.pyplot as plt
# obtain example dataset
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
# get the matplotlib default color cycle
cycle = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
# use pandas to plot by label
ax = None
for species, group in iris.groupby('species'): # group is a sub-dataset consisting of each "species"
ax = group.plot.scatter(
x='sepal_length',
y='sepal_width',
c=next(cycle), # specify color
label=species, # specify legend label
ax=ax) # update same axes object
@cswiercz
Copy link
Author

Replace iter with itertools.cycle if you expect more than 9 colors/labels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment