我想使用子图放置 3 个图。顶行有两个图,一个图将占据整个第二行。
我的代码在顶部两个图和下部图之间创建了间隙。我该如何纠正这个问题?
df_CI
Country China India
1980 5123 8880
1981 6682 8670
1982 3308 8147
1983 1863 7338
1984 1527 5704
fig = plt.figure() # create figure
ax0 = fig.add_subplot(221) # add subplot 1 (2 row, 2 columns, first plot)
ax1 = fig.add_subplot(222) # add subplot 2 (2 row, 2 columns, second plot).
ax2 = fig.add_subplot(313) # a 3 digit number where the hundreds represent nrows, the tens represent ncols
# and the units represent plot_number.
# Subplot …Run Code Online (Sandbox Code Playgroud) I\xc2\xb4ve 遇到以下问题,即我的颜色条覆盖了“打印”为 pdf 的纸质子图。
\n\n代码示例:
\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\n\nif __name__ == \'__main__\':\n\n titles = np.random.uniform(low=1, high=11, size=(1,10))\n temp = np.random.uniform(low=23, high=200, size=(10,10))\n ctf0102 = np.random.uniform(low=23, high=200, size=(10,10))\n ctf03 = np.random.uniform(low=23, high=200, size=(10,10))\n\n fig = plt.figure(figsize=(11.69,8.27), dpi=100)\n\n for num in range(len(titles)):\n\n ax = fig.add_subplot(3,4,num)\n\n im = ax.scatter(ctf03[1:,num], ctf0102[:,num], 12, temp[:,num], cmap=\'magma\')\n\n ax.set_title(titles[num])\n\n\n fig.text(0.5, -0.00, \'...\', ha=\'center\', fontsize=16)\n\n fig.text(-0.00, 0.5, \'...\', va=\'center\', rotation=\'vertical\', fontsize=16)\n\n cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n fig.colorbar(im, cax=cbar_ax)\n\n plt.tight_layout(pad=2)\n\n fig.savefig("example.pdf", …Run Code Online (Sandbox Code Playgroud) 我正在使用 matplotlib 绘制图表。当我使用以下代码在同一个图表中绘制它时:
def draw0(x, ys, labels):
plt.suptitle("big title")
i =0
for y in ys:
plt.plot(x, y, label=labels[i])
plt.scatter(x, y) # dots
plt.xticks(range(1, max(x) + 1))
plt.grid(True)
i+=1
plt.figlegend(loc="upper left")
plt.show()
return
x = [1,2,3,4,5]
y1 = [1,3,5,7,9]
y2 = [10,30,50,70,90]
y3 = [0.1,0.3,0.5,0.7,0.9]
draw0(x, [y1, y2, y3], ["chart1", "chart2", "chart3"])
Run Code Online (Sandbox Code Playgroud)
一切正常。 一个窗口中的图表 但我需要每个图表都位于单独的子图上。
我正在尝试这样做:
def draw11(x, ys, labels):
plt.figure()
plt.suptitle("big title")
i =0
for y in ys:
if i == 0:
ax = plt.subplot(len(ys),1, i+1)
else:
plt.subplot(len(ys), 1, i …Run Code Online (Sandbox Code Playgroud) 我正在尝试旋转每个子图的 x 轴标签。这是我的代码:
fig.set_figheight(10)
fig.set_figwidth(20)
ax.set_xticklabels(dr_2012['State/UT'], rotation = 90)
ax[0, 0].bar(dr_2012['State/UT'], dr_2012['Primary Total'])
ax[0, 0].set_title('Dropout Ratios 2012-2013 (Primary)')
ax[0, 1].bar(dr_2012['State/UT'], dr_2012['Upper Primary Total'])
ax[0, 1].set_title('Dropout Ratios 2012-2013 (Upper Primary)')
ax[1, 0].bar(dr_2012['State/UT'], dr_2012['Secondary Total'])
ax[1, 0].set_title('Dropout Ratios 2012-2013 (Secondary)')
ax[1, 1].bar(dr_2012['State/UT'], dr_2012['HS Total'])
ax[1, 1].set_title('Dropout Ratios 2012-2013 (HS)')
Run Code Online (Sandbox Code Playgroud)

平常的事情似乎都不适合我。我尝试过 ax.set_xticklabels 和 ax.tick_params。我还尝试使用 ax.get_xticklabels 循环遍历刻度,但即使这样也不起作用。它总是给我这个错误 -
AttributeError: 'numpy.ndarray' object has no attribute 'set_xticklabels'/'get_xticklabels'/'tick_params'
Run Code Online (Sandbox Code Playgroud)
我很茫然。为什么它不起作用?
如何为子图中的所有直方图添加全局图例?
下面的代码模仿了一些数据,我希望在图中的某处有一个全局图例。我正在底部思考,但会考虑更好的答案。它可以左对齐、居中或分散。
我如何添加全球图例?我尝试按照此处的fig.legend((v1, v2, v3), ('v1', 'v2', 'v3'), 'lower left')建议使用,但我认为这不适用于直方图。
使用Python 3.8
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
%matplotlib inline
v1=[3,1.1,2,5.2,4.9,2.6,3,0.5]
v2=[6.1,5.2,9.5,4.5]
v3=[0.1,1.4,0.5,1.2]
fig, axes = plt.subplots(4,2, figsize=(6.5,4.0), constrained_layout=True)
fig.suptitle('suptile')
mybins = [0,3,6,9,12]
mylist = [0,1,4,7]
for ii, ax in enumerate(axes.flat):
if ii in mylist:
data = [v1,v2,v3]
colors = ['blue', 'red', 'green']
labels = ['v1', 'v2', 'v3']
else:
data = [v1,v2]
colors = ['blue', 'red']
labels = ['v1', 'v2']
ax.hist(data, color=colors,edgecolor='black', alpha=0.5,
density=False, cumulative=False, …Run Code Online (Sandbox Code Playgroud) 我正在用Python学习乳腺癌分类数据集。我正在尝试为每个特征绘制直方图,如何将这些直方图分为三组?就像下面的截图一样:

这是我使用的代码:
from sklearn.datasets import load_breast_cancer # sample data
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = load_breast_cancer()
# Turn the feature data into a dataframe
df = pd.DataFrame(data.data, columns = data.feature_names)
# Add the target columns, and fill it with the target data
df["target"] = data.target
# display(df.head())
mean radius mean texture mean perimeter mean area mean smoothness mean compactness mean concavity mean concave points mean symmetry mean fractal dimension radius error …Run Code Online (Sandbox Code Playgroud) 正如标题所说,我正在尝试将网格函数的2变量切片(例如.jpg)保存为子图.我想使用.m文件执行此操作,因为我有许多图表要生成.我已经弄清楚如何在他们自己的数字上绘制视图,但我不能让他们正确地绘制成图中的子图.说明我的意思:
以下是各个图的输出:
3D网格:3D MATLAB网格图
XY视图:XY MATLAB网格视图
YZ视图:YZ MATLAB网格视图
XZ视图:XZ MATLAB网格视图
这是我的绘图代码(不工作):
%Ambiguity Surface
fid = figure(fnum);
axes1 = axes('Parent',fid);
view(axes1,[-62.5 28]);
grid(axes1,'on');
hold(axes1,'all');
msh = mesh(taux,fdy,z,'Parent',axes1);
xlabel ('Delay - seconds');
ylabel ('Doppler - Hz');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)');
fname = strcat(name,' (Ambiguity Function z(\tau;F_d))');
title(fname);
cb = colorbar('peer',axes1);
set(get(cb,'ylabel'),'String','Magnitude-Squared (dB)');
hold off;
printFig(fid,fnum,sname)
fnum = fnum + 1;
%Ambiguity Slices
fid = figure(fnum);
hold all;
subplot(2,1,1);
axes1 = axes();
grid(axes1,'on');
view(axes1,[90 0]);
msh = mesh(taux,fdy,z); …Run Code Online (Sandbox Code Playgroud) 与我们在 MATLAB 中使用 subplot 命令在单个图中绘制多个图类似,如何使用 Simulink 在同一图中绘制不同的图?
笔记:
有什么帮助吗?
我正在使用subplots函数将 8 列绘制成一个图形。然而,它显示
“IndexError:数组的索引太多”
# -*- coding: utf-8 -*-
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import style
df = pd.read_csv('XXXX', encoding='utf-8')
num = 0
for dim in ['A','B','C','D','E','F','G','H']:
fig, axes = plt.subplots(nrows=8, ncols=1)
df[dim].plot(ax=axes[num,0])
plt.xlabel(dim)
num += 1
plt.show()
Run Code Online (Sandbox Code Playgroud) 我有一个只包含数字列的pandas数据框,并且我正在尝试为所有功能创建单独的直方图
ind group people value value_50
1 1 5 100 1
1 2 2 90 1
2 1 10 80 1
2 2 20 40 0
3 1 7 10 0
3 2 23 30 0
Run Code Online (Sandbox Code Playgroud)
但是在我的现实生活数据中有50多个列,如何为所有列创建单独的图
我试过了
df.plot.hist( subplots = True, grid = True)
Run Code Online (Sandbox Code Playgroud)
它给了我一个重叠的不清楚的情节。
如何使用pandas subplots = True排列它们。下面的示例可以帮助我获取(2,2)网格中四列的图形。但对于所有50列来说,这都是一个漫长的方法
fig, [(ax1,ax2),(ax3,ax4)] = plt.subplots(2,2, figsize = (20,10))
Run Code Online (Sandbox Code Playgroud) 我需要添加两列和多行的子图。行不会固定,但对于一列,我想从一个数据集创建seaborn线图,对于第二列,我想为另一个数据集创建seaborn线图。
我已经尝试过以下但不起作用。
tips = sns.load_dataset("tips")
dataset2=tips
days = list(tips.drop_duplicates('day')['day'])
ggpec = gridspec.GridSpec(len(days ), 2)
axs = []
for i,j in zip(days,range(1,len(days)+1)):
fig = plt.figure(figsize=(20,4),dpi=200)
palette = sns.color_palette("magma", 2)
chart = sns.lineplot(x="time", y="total_bill",
hue="sex",style='sex',
palette=palette, data=tips[tips['day']==i])
chart.set_xticklabels(
chart.get_xticklabels(),
rotation=90,
minor=True,
verticalalignment=True,
horizontalalignment='right',
fontweight='light',
fontsize='large'
)
plt.title("Title 1",fontsize=18, fontweight='bold')
fig2 = plt.figure(figsize=(20,5),dpi=200)
palette = sns.color_palette("magma", 2)
chart = sns.lineplot(x="time", y="total_bill",
hue="sex",style='sex',
palette=palette, data=dataset2[dataset2['day']==i])
chart.set_xticklabels(
chart.get_xticklabels(),
rotation=90,
minor=True,
verticalalignment=True,
horizontalalignment='right',
fontweight='light',
fontsize='large'
)
plt.title("Title 2",fontsize=18, fontweight='bold')
plt.show()
Run Code Online (Sandbox Code Playgroud) 我试图将 Seaborn 基于时间的热图放置在条形图的顶部,指示每个箱/时间范围内的患者数量。我可以成功制作单独的热图和条形图,但将两者结合起来却无法按预期工作。
import pandas as pd
import numpy as np
import seaborn as sb
from matplotlib import pyplot as plt
# Mock data
patient_counts = [650, 28, 8]
missings_df = pd.DataFrame(np.array([[-15.8, 600/650, 580/650, 590/650],
[488.2, 20/23, 21/23, 21/23],
[992.2, 7/8, 8/8, 8/8]]),
columns=['time', 'Resp. (/min)', 'SpO2', 'Blood Pressure'])
missings_df.set_index('time', inplace=True)
# Plot heatmap
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(26, 16), sharex=True, gridspec_kw={'height_ratios': [5, 1]})
sb.heatmap(missings_df.T, cmap="Blues", cbar_kws={"shrink": .8}, ax=ax1, xticklabels=False)
plt.xlabel('Time (hours)')
# Plot line graph under heatmap to …Run Code Online (Sandbox Code Playgroud)