I wrote the basic operation of matplotlib with Jupyter Lab

This article is an article that I actually coded the basic operation of matplotlib described in Kame (@usdatascientist)'s blog (https://datawokagaku.com/python_for_ds_summary/) using Jupyter Lab.

Summary of basic operations of matplotlib

20th

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-3, 3, 10)
y = np.exp(x)
print(x)
print(y)
[-3.         -2.33333333 -1.66666667 -1.         -0.33333333  0.33333333
  1.          1.66666667  2.33333333  3.        ]
[ 0.04978707  0.09697197  0.1888756   0.36787944  0.71653131  1.39561243
  2.71828183  5.29449005 10.3122585  20.08553692]
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x7f0518676c50>]

png

Attach attached information

When drawing with matplotlib, you can add (or delete) various attached information. The ones I often use are as follows.

Label the x-axis with plt.xlabel ()

Label the y-axis with plt.ylabel ()

Give the figure a title with plt.title ()

Label the plot with plt.plot (label ='label') and add a legend with plt.legend ()

Add arbitrary ticks to the x-axis with plt.xticks ()

Add arbitrary ticks to the y-axis with plt.yticks ()

Erase the axis with plt.axis (‘off’)

plt.plot(x,y)
# plt.xlabel()Label the x-axis with
plt.xlabel('Efforts')
# plt.ylabel()Label the y-axis with
plt.ylabel('Earning')
# plt.title()Give a title to the figure with
plt.title('This is how your efforts earns')
Text(0.5, 1.0, 'This is how your efforts earns')

png

# plt.plot(label='label')でplotにlabelをつけ, plt.legend()To give a legend
plt.plot(x, y, label='Earning with effort')
plt.legend()
# plt.xticks()Add arbitrary ticks to the x-axis with
plt.xticks(np.arange(-3, 4, 0.5))
# plt.yticks()Attach arbitrary ticks to the y-axis with
plt.yticks([0, 5, 10, 20])
plt.show()

png

x = np.linspace(-3, 3, 10)
y1 = np.exp(x)
y2 = np.exp(x)*2
plt.plot(x, y1, label='first')
plt.plot(x, y2, label='second')
plt.legend()
<matplotlib.legend.Legend at 0x7f05182abc50>

png

plt.plot(x, y1, label='first')
plt.plot(x, y2, label='second')
plt.axis('off')
# plt.axis('off')Erase the axis with
plt.legend()
<matplotlib.legend.Legend at 0x7f05182f8e10>

png

21st

subplot

x = np.linspace(-3, 3, 10)
y1 = np.exp(x)
y2 = x*x

plt.subplot(1, 2, 1)
plt.plot(x, y1)

plt.subplot(1, 2, 2)
plt.plot(x, y2)
[<matplotlib.lines.Line2D at 0x7f0505d1d690>]

png

Object-oriented description

plt.figure object

fig = plt.figure()
type(fig)
matplotlib.figure.Figure




<Figure size 432x288 with 0 Axes>
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

ax1.plot(x, y1)
ax2.plot(x, y2)
[<matplotlib.lines.Line2D at 0x7f0505aead10>]

png

#Create a 1-by-2 plot Each axes object is returned as a list in axes
fig, axes = plt.subplots(nrows=1, ncols=2)
axes
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7f0505bd2650>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0505a22a10>],
      dtype=object)

png

fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
[<matplotlib.lines.Line2D at 0x7f0505894fd0>]

png

fig, axes = plt.subplots(nrows=3, ncols=3)
print(axes.shape)
(3, 3)

png

fig, axes = plt.subplots(nrows=3, ncols=3)
axes[1,2].plot(x,y2)
[<matplotlib.lines.Line2D at 0x7f05055cee90>]

png

fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].plot(x, y1, label='something')
axes[1].plot(x, y1)
axes[0].set_xlabel('xlabel1')
axes[0].set_ylabel('xlabel2')
axes[0].set_title('plot title')
axes[0].set_xticks([-3, -2, -1, 3])
axes[0].set_yticks([0, 10, 20])
axes[0].legend()
axes[1].axis('off')
(-3.3, 3.3, -0.9520004243731263, 21.08732441592866)

png

22nd

Adjust the size of the graph

x = np.linspace(-3, 3, 10)
y1 = np.exp(x)
y2 = np.exp(x)*2
fig, axes = plt.subplots()
axes.plot(x, y1)
[<matplotlib.lines.Line2D at 0x7f0505c7cb10>]

png

#In this case, a graph of 100 pixels x 100 pixels is displayed on the monitor.
fig, axes = plt.subplots(figsize=(1,1), dpi=100)
axes.plot(x, y1)
[<matplotlib.lines.Line2D at 0x7f0505308750>]

png

fig, axes = plt.subplots(figsize=(10, 3))
axes.plot(x, y1)
[<matplotlib.lines.Line2D at 0x7f05056641d0>]

png

Save as png

fig, axes = plt.subplots(2, 1, figsize=(10, 3))
axes[0].plot(x, y1, label='something')
axes[1].plot(x, x*x)

axes[0].set_title('first')
axes[1].set_title('second')

axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')

fig.savefig('savefig_sample.png')

png

fig, axes = plt.subplots(2, 1, figsize=(10, 3))
axes[0].plot(x, y1, label='something')
axes[1].plot(x, x*x)

axes[0].set_title('first')
axes[1].set_title('second')

axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')

plt.tight_layout() #Adjust the graph to make it easier to see

fig.savefig('savefig_sample.png')

png

fig, axes = plt.subplots()
axes.plot(x, y1, label='first')
axes.plot(x, y2, label='second')
axes.plot(x, y1+y2, label='first+second')
axes.legend()
<matplotlib.legend.Legend at 0x7f0505664f50>

png

Save as pdf

from matplotlib.backends.backend_pdf import PdfPages
pdf = PdfPages('savefig_sample.pdf')
from matplotlib.backends.backend_pdf import PdfPages

pdf = PdfPages('savefig_sample.pdf')

#------Graph creation-------
fig, axes = plt.subplots()
axes.plot(x, y1, label='first')
axes.plot(x, y2, label='second')
axes.plot(x, y1+y2, label='first+second')
axes.legend(loc=0)
#---------------------

#Save to pdf
pdf.savefig(fig)
#close processing (I will do it for the time being)
pdf.close()

png

Save a large number of graphs as pdf

pdf = PdfPages('savemultifig_sample.pdf')
for i in range(0, 10):
    #------Graph creation--------
    fig, axes = plt.subplots( )
    #It was designed so that the shape of the graph gradually changes. (Appropriate.)
    axes.plot(x, y1 + x*i)
    #Give it a title. Please confirm that you can search for characters in pdf.
    axes.set_title('ID:#{}'.format(i))
    #-----------------------

    #Save in for loop
    pdf.savefig(fig)

#Close after loop
pdf.close()

png

png

png

png

png

png

png

png

png

png

23rd

How to decorate the graph

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-3, 3, 10)
y = np.exp(x)
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f050476fd90>]

png

color: Graph line color ⇨ Specify a color name such as ‘red’ or ‘green’. You can use acronyms like ‘r’ and ‘g’.

lw (line width): Line thickness ⇨ Number. Please make it the size you like

ls (line style): Line type ⇨ Specify as ‘-’ or ‘–’. Either of these two is often used.

marker: Marker type ⇨ Specify as ‘o’ or ‘x’. The shape of the marker changes.

markersize: Marker size ⇨ Number. Please make it the size you like

markerfacecolor: Marker color ⇨ Specify the color name such as ‘red’ or ‘green’. You can use acronyms like ‘r’ and ‘g’.

markeredgecolor: Color in the marker frame ⇨ Specify the name of the color such as ‘red’ or ‘green’. You can use acronyms like ‘r’ and ‘g’.

markeredgewidth: Thickness of the marker frame ⇨ Number. Please make it the size you like

alpha: Plot transparency ⇨ Specify between 0 and 1 with float. The closer it is to 0, the higher the transparency.

plt.plot(x, y, color='red', lw=5, ls='--', marker='o', markersize=15, markerfacecolor='yellow', markeredgecolor='blue',
        markeredgewidth=4, alpha=0.5)
[<matplotlib.lines.Line2D at 0x7f05050fbd90>]

png

Scatter plot: plt.scatter ()

import pandas as pd
df = pd.read_csv('train.csv')
plt.scatter(df['Age'], df['Fare'], alpha=0.3)
<matplotlib.collections.PathCollection at 0x7f04b99fbf50>

png

Histogram: plt.hisgt ()

plt.hist(df['Age'])
plt.show()
/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/histograms.py:829: RuntimeWarning: invalid value encountered in greater_equal
  keep = (tmp_a >= first_edge)
/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/histograms.py:830: RuntimeWarning: invalid value encountered in less_equal
  keep &= (tmp_a <= last_edge)

png

plt.hist(df['Age'], bins=50)
plt.show()

png

Box plot: plt.boxplot ()

df = df.dropna(subset=['Age'])
plt.boxplot(df['Age'])
plt.show()

Recommended Posts

I wrote the basic operation of matplotlib with Jupyter Lab
I wrote the basic operation of Pandas with Jupyter Lab (Part 2)
I wrote the basic grammar of Python with Jupyter Lab
I wrote the basic operation of Seaborn in Jupyter Lab
I wrote the basic operation of Numpy in Jupyter Lab.
Align the size of the colorbar with matplotlib
Build the execution environment of Jupyter Lab
Increase the font size of the graph with matplotlib
I checked the list of shortcut keys of Jupyter
The basis of graph theory with matplotlib animation
Code for checking the operation of Python Matplotlib
Visualize the behavior of the sorting algorithm with matplotlib
Basic operation of pandas
Basic operation of Pandas
I tried to summarize the basic form of GPLVM
I measured the performance of 1 million documents with mongoDB
Summary of the basic flow of machine learning with Python
[Python, ObsPy] I wrote a beach ball with Matplotlib + ObsPy
Get the operation status of JR West with Python
[Introduction to Python] Basic usage of the library matplotlib
Adjust the ratio of multiple figures with the matplotlib gridspec
I wrote you to watch the signal with Go
I want to plot the location information of GTFS Realtime on Jupyter! (With balloon)
I tried to find the entropy of the image with python
I tried "gamma correction" of the image with Python + OpenCV
I wrote GP with numpy
I wrote the code for Japanese sentence generation with DeZero
I tried to find the average of the sequence with TensorFlow
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I evaluated the strategy of stock system trading with Python.
I want to get the operation information of yahoo route
I implemented the FloodFill algorithm with TRON BATTLE of CodinGame.
Try to automate the operation of network devices with Python
Let's visualize the number of people infected with coronavirus with matplotlib
Change the theme of Jupyter
Change the style of matplotlib
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I compared the speed of Hash with Topaz, Ruby and Python
I tried scraping the ranking of Qiita Advent Calendar with Python
I tried standalone deployment of play with fabric [AWS operation with boto] [Play deployment]
I tried to automate the watering of the planter with Raspberry Pi
[Python] I wrote the route of the typhoon on the map using folium
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I want to output the beginning of the next month with Python
I wrote the code to write the code of Brainf * ck in python
I tried to expand the size of the logical volume with LVM
I want to check the position of my face with OpenCV!
I tried running the DNN part of OpenPose with Chainer CPU
I checked the image of Science University on Twitter with Word2Vec.
I tried to improve the efficiency of daily work with Python
I investigated the mechanism of flask-login!
About the basic type of Go
I liked the tweet with python. ..
I wrote the queue in Python
Unravel the mystery of matplotlib specgram
About the size of matplotlib points
I wrote the stack in Python
Basic study of OpenCV with Python
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
I replaced the numerical calculation of Python with Rust and compared the speed
[I touched the Raspberry Pi (1)] I summarized the basic operations of Minecraft Pi Edition (2015.5.23 pre-release)