Skip to content

Instantly share code, notes, and snippets.

@martinapugliese
Last active March 27, 2018 16:44
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 martinapugliese/ac3aea6a566b9080255f7e0f7d152626 to your computer and use it in GitHub Desktop.
Save martinapugliese/ac3aea6a566b9080255f7e0f7d152626 to your computer and use it in GitHub Desktop.

Pyplot reference stuff

Those things that I always forget how to do.

import pyplot as plt

Matplotlib styles

Can do plt.style.available to see all available styles; and to change it do plt.style.use('classic'). xkcd is not technically a style, and can be coupled with the styles: use plt.xkcd() to enable it on all subsequent plots, a with in front to only use it on current plot.

Pie charts

Because everybody hates them, right?

colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']

plt.pie([30.5, 19.5, 10, 40], 
         autopct='%1.1f%%',
        shadow=False, startangle=90, colors=colors)
plt.axis('equal')

plt.title('Pie title')
plt.show();

Two y axes on the same figure

Also colours the axis label same as the line. Uses a dataframe.

# Two y axes

df = pd.DataFrame({'x': range(10), 'y1': np.random.randint(0, 100, size=10), 'y2': np.random.randint(0, 100, size=10)})

fig, ax1 = plt.subplots(figsize=(15, 10))

df.plot.line('x', 'y1', marker='o', lw=1, ax=ax1, legend=False)
plt.xticks(rotation=70)
ax1.set_ylabel('y1', color='r')

ax2 = ax1.twinx()

df.plot.line('x', 'y2', marker='o', lw=2, c='k', ax=ax2, legend=False)
plt.xticks(rotation=70)
ax2.set_ylabel('y2', color='k', rotation=270)

ax1.grid()
ax2.grid()

plt.show();

Log scale, get the minor ticks

From this SO answer.

fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([10, 50, 100, 500])
ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
plt.show();

The problem is also that the ggplot style which doesn't seem to be able to get no grid but yes the ticks. With ply.style.use('classic') this works fine:

fig1, ax1 = plt.subplots()
ax1.scatter(x, y)
ax1.set_xscale('log')
ax1.set_yscale('log')
#ax1.set_xticks([10, 50, 100, 500, 1000, 5000])
#ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax1.get_xaxis().get_major_formatter().labelOnlyBase = False
#ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

plt.show();

Have also tried to work with the rcParam xaxis.minor.visible as per the issue, but makes no difference.

Scatter with size based on column and size legend specified

plt.scatter(x, y, s=size*10)

#make a legend:
pws = [0, 15, 20, 25, 30, 35, 50, 100]
for pw in pws:
    plt.scatter([], [], s=pw*10, c="k",label=str(pw))

h, l = plt.gca().get_legend_handles_labels()
plt.legend(h[1:], l[1:], labelspacing=1.2, title="size", borderpad=1,
            frameon=True, framealpha=0.6, edgecolor="k", facecolor="w")

plt.grid()
plt.show();

Scatter with color based on colour and chosen colour map

Note that sharex is used due to a bug in pandas, which kills xticks when colour is used

df.plot.scatter('x', 'y', c='c', cmap="viridis", sharex=False)

plt.ylim(0, 20, 1)
plt.yticks(np.arange(0, 21, 5))
plt.xticks(np.arange(0, 105, 10))
plt.grid()
plt.colorbar()
plt.show();

Label for all but one curve

Use empty string label=''

Plot with insets

This is from the docs.

# create some data to use for the plot
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05)               # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt  # colored noise

# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Gaussian colored noise')

# this is an inset axes over the main axes
a = plt.axes([.65, .6, .2, .2], facecolor='y')
n, bins, patches = plt.hist(s, 400, normed=1)
plt.title('Probability')
plt.xticks([])
plt.yticks([])

# this is another inset axes over the main axes
a = plt.axes([0.2, 0.6, .2, .2], facecolor='y')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])

plt.show();

To share y axis cross figures

Contains how to put global title and single titles, this from the docs, manipulated a bit.

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

# Two subplots, unpack the axes array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(20, 10))
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

ax1.set_ylabel('y label')
ax1.set_xlabel('x label')
ax2.set_xlabel('x label')

f.suptitle("Title centered above all subplots")

plt.show();

To use differnet xlims though as changing one changes the other in this case, if not wanted sharey=False.

4 quadrants plots

# Log
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 6))
fig.suptitle("Title centered above all subplots", fontsize=14)

ax1.loglog(x, y, marker='o', label='users')
ax1.set_ylabel('Cumulative counts')

ax2.loglog(x, y, marker='o', label='products')

ax3.loglog(x, y, marker='o', label='swipes')
ax3.set_xlabel('Month index')
ax3.set_ylabel('Cumulative counts')

ax4.loglog(x, y, marker='o', label='products swiped')

plt.xlim(10, 50)
#plt.title('Growth curves in log-log scale')
plt.xlabel('Month index')

plt.grid()

plt.legend()

plt.show();

Grid below graph elements

The zorder of graph elements has to be higher than that of the grid, 3 and 0 respectively work.

plt.plot(x, y, zorder=3)
plt.grid(zorder=0)
plt.show();

Various

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