如何并排制作两个图[重复]
- 2025-03-13 09:21:00
- admin 原创
- 15
问题描述:
我在 matplotlib 上找到了以下示例:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'ko-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
我的问题是:我需要做哪些改变才能使各个情节并列?
解决方案 1:
将您的子图设置更改为:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
的参数subplot
为:行数、列数以及当前所在的子图。 So1, 2, 1
表示“1 行 2 列的图形:转到第一个子图。” Then1, 2, 2
表示“1 行 2 列的图形:转到第二个子图。”
您当前请求的是 2 行 1 列(即,一列位于另一列之上)布局。您需要改为请求 1 行 2 列布局。执行此操作后,结果将是:
为了尽量减少子图的重叠,你可能需要加入:
plt.tight_layout()
演出前。收益:
解决方案 2:
查看此页面:http ://matplotlib.org/examples/pylab_examples/subplots_demo.html
plt.subplots
类似。我认为它更好,因为设置图形参数更容易。前两个参数定义布局(在您的例子中为 1 行,2 列),其他参数更改图形大小等功能:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()
解决方案 3:
当在一个方向上堆叠子图时,如果您只是创建几个轴,matplotlib 文档建议立即解包。
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(20,8))
sns.histplot(df['Price'], ax=ax1)
sns.histplot(np.log(df['Price']),ax=ax2)
plt.show()
解决方案 4:
您可以使用-matplotlib.gridspec.GridSpec
检查 - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html
下面的代码在右侧显示热图,在左侧显示图像。
#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2)
fig = plt.figure(figsize=(25,3))
#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)
#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")
plt.imshow(image)
plt.show()
输出图像
解决方案 5:
基本上,我们必须定义需要多少行和多少列。假设我们总共有 4 个分类列需要绘制。让我们在 2 行 2 列中总共绘制 4 个图。
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
sns.set_style("darkgrid")
%matplotlib inline
#15 by 15 size set for entire plots
plt.figure(figsize=(15,15));
#Set rows variable to 2
rows = 2
#Set columns variable to 2, this way we will plot 2 by 2 = 4 plots
columns = 2
#Set the plot_count variable to 1
#This variable will be used to define which plot out of total 4 plot
plot_count = 1
cat_columns = [col for col in df.columns if df[col].dtype=='O']
for col in cat_columns:
plt.subplot(rows, columns, plot_count)
sns.countplot(x=col, data=df)
plt.xticks(rotation=70);
#plot variable is incremented by 1 till 4, specifying which plot of total 4 plots
plot_count += 1
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD