Python application: data visualization # 2: matplotlib

Visualize one type of data

Plot the data on the graph

Matplotlib
#It has a lot of functions for visualizing data.
matplotlib.pyplot.plot(Data corresponding to the x-axis,Data corresponding to the y-axis)
#You can easily create a graph by associating data with the x-axis (horizontal axis) and y-axis (vertical axis) of the graph.
matplotlib.pyplot.show() #Display the created graph on the screen

Set the display range of the graph

When creating a graph using matplotlib.pyplot The display range of the graph is set automatically.

The min () and max () of the data (list) assigned to each axis are All parts of the data are automatically visualized because the display range is the minimum and maximum values.

You may want to display only part of the graph. In that case Use the program below.

matplotlib.pyplot.xlim([Starting value,End value])
#Set the display range of the graph
#xlim is a function that specifies the range of the x-axis. Use ylim to specify the y-axis range

Name the elements of the graph

matplotlib.pyplot has many methods that allow you to name various elements of your graph.

matplotlib.pyplot.title("title") # グラフのtitle
matplotlib.pyplot.xlabel("x-axis label") # グラフのx-axis label

Show grid on graph

The grid (scale line) is the display method.

matplotlib.pyplot.grid(True) #Display of grid(None by default)

Set the scale on the axis of the graph

When you create a graph, the x-axis and y-axis are automatically graduated. The sharpness of each axis is good and the scale is attached. If you want to set the scale, use the following program.

matplotlib.pyplot.xticks(Position to insert the scale,Character string of the scale to be displayed)
#Set scale on x-axis
import matplotlib.pyplot as plt

plt.plot([2,3,9,1,5])
plt.xticks([0.7,2.1,3.5], ["i","ii","iii"])
plt.show()

Visualize multiple data 1

Plot multiple data on one graph

Sometimes you want to display multiple data on one graph. Each data can be displayed (plot) in different colors on the graph.

matplotlib.pyplot.plot(x, y, color="Color specification")
#Describe each data you want to display in different colors, and specify different variables for each.
#Each time you do this, a plot will be drawn on the graph.
# color=Even without it, you can specify the color with the third argument.

The color of the plot is specified by the HTML color code.

HTML color code

It is a code that expresses the color with 6-digit hexadecimal numbers (0-9 and A-F alphanumeric characters) following #, such as 0000ff. AA0000 is a color close to red.

You can also specify the following characters.

Color code color
b Blue
g Green
r Red
c cyan
m Magenta
y yellow
k black
w White

Set series label

matplotlib.pyplot.legend() #Set and display the series label (legend).

It is the lower left part of the figure below.

image.png

There are two ways to set the series label.

# 1.Automatically determine what is displayed on the series label

matplotlib.pyplot.plot(x, y1, label="Label name 1")
matplotlib.pyplot.plot(x, y2, label="Label name 2")
matplotlib.pyplot.legend()
# 2.Label elements that already exist

matplotlib.pyplot.plot(x, y1)
matplotlib.pyplot.plot(x, y2)
matplotlib.pyplot.legend(["Label name 1", "Label name 2"])

Method 1 explicitly specifies the label for the element to be plotted. In method 2, the relationship between the element and the label is not explicit. Not recommended as it can cause confusion.

Visualize multiple data 2

How to create multiple graphs and edit them

Set the size of the figure

matplotlib.pyplot.figure()
#Methods that can operate everything in the figure
matplotlib.pyplot.figure(figsize=(Horizontal size,Vertical size))
#Size with figsiza(In inches)Specify.
#Specify the horizontal and vertical sizes in inches. If omitted, figsize=(8, 6)Will be.

Create subplot

Using the subplots (axes), in the figure (figure) You can generate any number of graphs and draw multiple graphs. You can also manipulate the graph for each subplot.

When adding a subplot (axes object) to a diagram (figure object) Specify the add_subplot () method for the figure object Specifies the layout that divides the figure and the position of the subplot within it.

add_subplot(Number of lines,Number of columns,What number)

#Number of lines: How many lines should the figure be divided into?
#Number of columns: How many columns will the figure be divided into?
#Number: 1 from top left to right in the figure, 2, 3 ...What number do you add?
import matplotlib.pyplot as plt
import numpy as np


#Create figure object
fig = plt.figure(figsize=(4, 4))
#Divide the axes object into 2 rows and 3 columns and add a graph at the bottom right
ax = fig.add_subplot(2, 3, 6)

#  y=Draw x graph on axes object
x = np.linspace(0, 100)
y = x
ax.plot(x, y)

#Fill in the blanks with subplots to make the position of the graph easier to understand
for i in range(6):
    if i == 5:
        continue
    fig.add_subplot(2, 3, i+1)


plt.show()

image.png

Adjust the margins around the subplot

matplotlib.pyplot.subplots_adjust(wspace=Horizontal spacing width, hspace=Vertical spacing width)
#There is no limit to the value that sets the margin, but it is automatically corrected so that it does not jump out of the graph area.

Set the display range of the graph in the subplot

You can set the graph display range for each subplot. In addition, the x-axis and y-axis can be set respectively.

#Let the subplot object be the variable ax.

ax.set_xlim([minimum value,Maximum value]) #Set the x-axis display range
ax.set_ylim([minimum value,Maximum value]) #Set the y-axis display range
#For example, to set the x-axis display range to 0 to 1, write as follows.
ax.set_xlim([0, 1])

Name the graph elements in the subplot

You can set elements such as titles and labels for each subplot. There is a little habit in the way.

#Let the subplot object be the variable ax.

ax.set_title("title") # グラフのtitleを設定する
ax.set_xlabel("x-axis name") #Set x-axis label
ax.set_ylabel("y-axis name") #Set the y-axis label

Show grid on graph in subplot

#Let the subplot object be the variable ax.
ax.grid(True)

Set the scale on the axis of the graph in the subplot

You can set the axis scale for each subplot.

#Let the subplot object be the variable ax.

ax.set_xticks([List of insertion positions]) #Position of the scale to be inserted on the x-axis
ax.set_xticklabels([List of tick labels]) #Tick label to insert on x-axis

#Describe the position of the scale to be inserted and the label of the scale in a list type.
#It is also possible to convert it to a list type variable in advance.

Recommended Posts

Python application: data visualization # 2: matplotlib
Python application: data visualization part 1: basic
Python Application: Data Visualization Part 3: Various Graphs
Data visualization method using matplotlib (1)
Data visualization method using matplotlib (2)
Data visualization method using matplotlib (+ pandas) (5)
Python Application: Data Handling Part 3: Data Format
Data visualization method using matplotlib (+ pandas) (3)
Easy data visualization with Python seaborn.
Data analysis starting with python (data visualization 1)
Data visualization method using matplotlib (+ pandas) (4)
Data analysis starting with python (data visualization 2)
Implement "Data Visualization Design # 2" with matplotlib
Python application: Data cleansing # 2: Data cleansing with DataFrame
Python visualization tool for data analysis work
Data analysis python
#Python basics (#matplotlib)
[Python] Web application from 0! Hands-on (4) -Data molding-
My matplotlib (python)
Recommendation of Altair! Data visualization with Python
[python] Read data
[Scientific / technical calculation by Python] Histogram, visualization, matplotlib
Read Python csv data with Pandas ⇒ Graph with Matplotlib
Implement "Data Visualization Design # 3" with pandas and matplotlib
Python Application: Data Handling Part 2: Parsing Various Data Formats
Data analysis with python 2
Visualization memo by Python
Data analysis using Python 0
Data analysis overview python
Various Python visualization tools
Data cleaning using Python
Heatmap with Python + matplotlib
Data visualization with pandas
Python data analysis template
[Python tutorial] Data structure
[Python] Sorting Numpy data
Installation of matplotlib (Python 3.3.2)
Application of Python 3 vars
Data analysis with Python
Logistics visualization with Python
Python application: Pandas # 3: Dataframe
Power BI visualization of Salesforce data entirely in Python
[Scientific / technical calculation by Python] Logarithmic graph, visualization, matplotlib
[Scientific / technical calculation by Python] Polar graph, visualization, matplotlib
Sample data created with python
My python data analysis container
Handle Ambient data in Python
Graph Excel data with matplotlib (1)
Python application: Pandas Part 1: Basic
data structure python push pop
Python application: Pandas Part 2: Series
Use matplotlib on Ubuntu 12 & Python
Python for Data Analysis Chapter 4
Display UTM-30LX data in Python
Get Youtube data with python
Visualization of data by prefecture
Data Science Cheat Sheet (Python)
[Python] Notes on data analysis
My python data analytics environment
Graph Excel data with matplotlib (2)
Python data analysis learning notes