Road to Data Analyst/Python
[matplotlib] Merge two graphs into one
kimbop
2023. 3. 1. 14:24
twinx()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
f, ax = plt.subplots(1,1)
x_values = [0,1,2,3,4,5]
y_values = [0,1,4,9,16,25]
ax.plot(x_values, y_values, color='red', linestyle='dashed', linewidth=1, marker="o")
x2_values = [0,1,2,3,4,5]
y2_values = [1000,2000,3000,4000,5000,6000]
ax2=ax.twinx()
ax2.plot(x2_values, y2_values, color='darkblue', linestyle='dashed', linewidth=1, marker='x')
plt.show()
As you can see the result, you can realize that the y ticks of ax is written left-side, while the y ticks of ax2 is written right-side.
- When I would like to show two graphs into one figure / area, we can use "twinx()"
- plt.subplots(n, m): make several sections; n number of row, m number of column.
- marker: shape of each point
- ax.twinx(): merge graph (ax2) with another graph(ax)
One f, several ax
fig = plt.figure()
ax = fig.add_subplot(2,1,2)
x_values = [0,1,2,3,4,5]
y_values = [0,1,4,9,16,25]
ax.plot(x_values, y_values, color='red', linestyle='dashed', linewidth=1, marker="o")
ax2 = fig.add_subplot(2,1,1)
x2_values = [0,1,2,3,4,5]
y2_values = [1000,2000,3000,4000,5000,6000]
ax2.plot(x2_values, y2_values, color='darkblue', linestyle='dashed', linewidth=1, marker="x")
plt.show()
As you can see the code and its result, we can conclude that we can change the location of the graph as we want.
- define ax2 = fig.add_subplot(2,1,1) → There will be sections for two rows and one columns, and this ax2 graph will be written on the first part of the section.