[PYTHON] Grammar summary that is often forgotten with matplotlib

This is a memo that is often forgotten when dealing with the Python drawing library "matplotlib".

2016-11-11 「ax.Added "annotate characters and arrows" and fine-tuned headings
2016-11-11 Added "Locator scale position"
2016-12-16 Updated "Locator Scale Position"
2017-02-11 Added "out of frame" method for legend

--Environment

- Anaconda 4.0.0 (Python 2.7.13)
- CentOS 6.5

--Scheduled to be added in the future (2016-11-11)

- cmap
- plt.xlim() = ax.set_xlim()

** Tend to forget plot **

** plt.fill_between ** fill

Ranged fill plot

plt.fill_between(time, value1, value2)
plt.fill_betweenx(depth, profile1, profile2) #When writing a vertical distribution

fill_demo http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill_between

** plt.errorbar ** error bar

Plot with error bars

plt.errorbar(time, value, yerr=value_std)
plt.errorbar(profile, depth, xerr=profile_std) #For vertical distribution

errorbar_demo http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.errorbar

** df.plot ** Plot for pandas

Plot of pandas.DataFrame

df.plot(x='time', y='value1', ls='-', marker='o', color='k')
df.plot(x='time', y=['value1','value2']) #Draw multiple lines on one graph.
df.plot(x='time', y=['value1','value2'], subplots=True, layout=(1,2)) # ax[0], ax[1]Depicted in each

--x is ʻindex by default, so it can be omitted, but I don't know how to specify it as y. (Y ='index'` will result in an error) --y Omission plots all columns

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html

** plt.semilogy ** Logarithmic axis plot

plt.semilogy(x, y) #y-axis is logarithmic
plt.semilogx(x, y) #x-axis is logarithmic
plt.loglog(x, y) #Log-log
ax.plot(x, y)
ax.set_xscale("log") #Can be set later
ax.set_yscale("log", nonposy='clip') #What to do if it becomes negative.'mask'There is also

http://matplotlib.org/examples/pylab_examples/log_demo.html http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.semilogy

** ax.annotate ** letters and arrows

ax.annotate('arrowstyle', 
            xy=(0, 1), xycoords='data',      #The tip of the arrow(xy)Axle value(data)Specified by
            xytext=(-50, 30), 
            textcoords='offset points',      #Character position(xytext)The relative distance from the tip of the arrow(offset points)Specified by
            arrowprops=dict(arrowstyle="->")
            )

annotation_demo2_00 http://matplotlib.org/examples/pylab_examples/annotation_demo2.html

** Tend to forget axis setting **

** ax.set_xticklabels ([]) ** Erase labels

Erase the axis label (number or date part)

fig, ax = plt.subplots(1,2)

ax[0].set_xticklabels([]) #Erase the x-axis in the figure above

** DateFormatter ** Change date format

Change the time axis format

from matplotlib.dates import DateFormatter

ax.xaxis.set_major_formatter(DateFormatter('%m/%d\n%H:%M'))

http://matplotlib.org/api/dates_api.html#matplotlib.dates.DateFormatter

** Locator ** Scale position

** Value axis **

from matplotlib import ticker

ax.xaxis.set_major_locator(ticker.MultipleLocator(20))           #Every 20
ax.xaxis.set_major_locator(ticker.MaxNLocator(5))                #Up to 5

** Time axis **

from matplotlib import dates as mdates

ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=8))   #Up to 8
ax.xaxis.set_major_locator(mdates.HourLocator(12))               #12 o'clock
ax.xaxis.set_major_locator(mdates.HourLocator(interval=24))      #Every 24 hours
ax.xaxis.set_major_locator(mdates.DayLocator(np.arange(1,31,7))) #Weekly

** Forgotten options **

** plt.savefig ** Save

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

** Background transparency **

plt.savefig(filename, transparent=True) # default: False

** Small margins **

plt.savefig(filename, bbox_inches='tight')

** plt.legend ** Legend

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

** Change the arrangement **

plt.legend(ncol=2) #The number of each legend side by side (default): 1)

** Number of markers **

plt.legend(numpoints=1) #Unify the number of markers (default):For some reason 2)

Match legend points with matplotlib @ halm

** Put out of the frame **

plt.legend(bbox_to_anchor=(1.01,1), loc=2, borderaxespad=0)

http://matplotlib.org/users/legend_guide.html#legend-location

** Other **

** plt.rcParams [] ** Settings

If you set the font etc. before drawing, it will be quick.

plt.rcParams["font.size"] = 12 #Change font size (default): 10?)

http://matplotlib.org/users/customizing.html

** matplotlibrc ** default settings

Or it's easier to change the default settings, so edit matplotlibrc

matplotlibrc


legend.numpoints = 1

** plt.style.use ** style

Overall design changes

plt.style.use('ggplot')

Reference page

-Personal note: Adjusting the graph using matplotlib @ hysterect -[Python] Customize Colormap when drawing graphs with matplotlib @ kenmatsu4

Recommended Posts

Grammar summary that is often forgotten with matplotlib
Grammar summary often used in pandas
matplotlib summary
Summary of operations often performed with asyncpg
Boto3 (manipulate AWS resources with Python library) API that is often used privately
Rebooting vhost or Apache, which is often forgotten
blockdiag grammar summary
Animation with matplotlib
Japanese with matplotlib
Animation with matplotlib
Histogram with matplotlib
Animate with matplotlib
String manipulation with python & pandas that I often use
Note that writing like this with ruby is writing like this with python