如何复制维基百科的情节?

2024-09-28 22:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想复制使用Python和pandas链接的情节。你知道吗

enter image description here

下面是数据框。你知道吗

df = pd.DataFrame(
             {"Sex":["Male"]*8+["Female"]*6,
            "Metabolic Rates":[525.8,605.7,843.3,1195.5,1945.6,2135.6,2308.7,
             2950,727.7,1086.5,1091,1361.3,1490.5,1956.1]})

我试图用matplotlib的错误条来实现它,但似乎不起作用。你知道吗

import numpy as np
x = [1,2,3,4,5,6,7,8]
dy = 894.372699158466
y = df.loc[df["Sex"]=="Male"]["Metabolic Rates"]
plt.errorbar(x, y, yerr=dy, fmt='o');

我只得到这个图:

enter image description here


Tags: 数据dataframepandasdfmatplotlib链接malefemale
2条回答

你可以这样画:

mean_male = df[df['Sex'] == 'Male'].mean().iloc[0]
mean_female = df[df['Sex'] == 'Female'].mean().iloc[0]
std_male = df[df['Sex'] == 'Male'].std().iloc[0]
std_female = df[df['Sex'] == 'Female'].std().iloc[0]

fig = plt.figure()
ax = fig.gca()
plt.plot(df.Sex, df['Metabolic Rates'], marker='.', linestyle='', color='black', markersize=12)
plt.errorbar(['Male', 'Female'], [mean_male, mean_female], yerr=[std_male, std_female], fmt='o', color='red')

当然,更多的格式是可选的。例如,绘制红色箭头需要plt.annotate。你知道吗

为了充分使用pandas功能,我建议重新格式化df。使用列或索引是在pandas中聚合数据的一种很好的方法。 例如,您可以这样格式化您的df:

df_new = pd.DataFrame({'Male': df[df.Sex == 'Male'].iloc[:, 1], 'Female': df[df.Sex == 'Female'].reset_index(drop=True).iloc[:, 1]})

(我想使用groupbyaggregate还有一种更简单的方法。)
现在您可以很容易地获得所有具有df.std()df.mean()的列所需的信息,如stdmean。也可以使用前端。你知道吗

import numpy as np
import matplotlib.pyplot as plt

# Create the data
mr_m = [525.8, 605.7, 843.3, 1195.5, 1945.6, 2135.6, 2308.7, 2950]
mr_f = [727.7, 1086.5, 1091, 1361.3, 1490.5, 1956.1]
mean_f = np.mean(mr_f)
mean_m = np.mean(mr_m)
std_f = np.std(mr_f)
std_m = np.std(mr_m)

# Create a figure
fig = plt.figure()
ax = fig.add_subplot(111)

# Set Layout
ax.set_xlim([0.4, 2.6])
ax.set_xticks([1, 2])
ax.set_xticklabels(['Female', 'Male'])
ax.set_ylabel('Metabolic Rate')

# Plot the data
ax.plot(np.ones_like(mr_f), mr_f, 'ko') #  k -> blacK, o-> plot just the datapoints
ax.plot(2 * np.ones_like(mr_m), mr_m, 'ko')
ax.plot(1, mean_f, 'ro')
ax.plot(2, mean_m, 'ro')

# Plot the arrows and the text with *annotate()*, some tuning on the values
# necessary to get the right offsets
# *annotate()* calls *FancyArrowPatch* to plot the arrows, could be used directly 
ax.annotate('', xy=(1.1, mean_f - std_f / 2),
            xytext=(1.1, mean_f + std_f / 2),
            arrowprops=dict(arrowstyle='<->', color='r'))
ax.annotate('Female\nStd. Dev.={}'.format(int(std_f)), xy=(1.15, mean_f -100))

ax.annotate('', xy=(2.1, mean_m - std_m / 2),
            xytext=(2.1, mean_m + std_m / 2),
            arrowprops=dict(arrowstyle='<->', color='r'))
ax.annotate('Male\nStd. Dev.={}'.format(int(std_m)), xy=(2.15, mean_m -100))

相关问题 更多 >