Skip to content

Instantly share code, notes, and snippets.

@dlebech
Last active March 13, 2020 15:29
Show Gist options
  • Save dlebech/9afcce3cbd821d2651108279eff5fdf3 to your computer and use it in GitHub Desktop.
Save dlebech/9afcce3cbd821d2651108279eff5fdf3 to your computer and use it in GitHub Desktop.
Matplotlib useful one liners that I always forget
# Matplotlib
# Creating a list of colors (e.g. for a bar chart)
# "Blues" is the colormap. It can be any colormap
# https://matplotlib.org/examples/color/colormaps_reference.html
colors = [matplotlib.colors.to_hex(c) for c in plt.cm.Blues(np.linspace(0, 1, len(some_dataframe.index)))]
# Globally adjusting DPI and figure size
matplotlib.rcParams['figure.dpi'] = 100
matplotlib.rcParams['figure.figsize'] = [6.0, 4.0]
# Setting a different global style
plt.style.use('ggplot')
# Rotate x tick labels, three options
ax.set_xticklabels(ax.get_xticks(), rotation=60)
ax.set_xticklabels(ax.get_xticklabels(), rotation=60)
plt.xticks(rotation=60) # Suggested by most SO answers but doesn't always work...
# Format axes with millions (e.g. 1.1M, 1.2M etc)
def millions(x, pos):
return '{:0.1f}M'.format(x*1e-6)
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(millions))
# Set log scale on an axes object
ax.set_yscale('log', nonposy='clip')
# Make multiple aggregations and rename the multi-index columns
# resulting from this aggregation
df.groupby('something').agg({
'column1': ['count', 'median']
})
df.columns = ['_'.join(col).strip() for col in df.columns.values]
# There will now be a column1_count and column1_median column
# Move legend to the right of the graph
plt.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment