【发布时间】:2019-05-08 07:40:00
【问题描述】:
我正在编写一个脚本,该脚本根据节点的数量接收多个输入、解析数据并多次调用绘图函数。
问题是我多次调用我的绘图函数(见下面的代码),但我不知道如何解决这个问题。我看到了this solution,但这不是我的情况(或者我不知道如何申请我的情况)。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set(style="whitegrid")
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4, figsize=(16, 4))
plt.tight_layout()
def plot_data(df, nodes):
global ax1, ax2, ax3, ax4
if nodes == 10:
plt.subplot(141)
ax1 = sns.kdeplot(df['Metric'], cumulative=True, legend=False)
ax1.set_ylabel('ECDF', fontsize = 16)
ax1.set_title('10 Nodes')
elif nodes == 20:
plt.subplot(142)
ax2 = sns.kdeplot(df['Metric'], cumulative=True, legend=False)
plt.setp(ax2.get_yticklabels(), visible=False)
ax2.set_title('20 Nodes')
elif nodes == 30:
plt.subplot(143)
ax3 = sns.kdeplot(df['Metric'], cumulative=True, legend=False)
plt.setp(ax3.get_yticklabels(), visible=False)
ax3.set_title('30 Nodes')
elif nodes == 40:
plt.subplot(144)
ax4 = sns.kdeplot(df['Metric'], cumulative=True, legend=False)
plt.setp(ax4.get_yticklabels(), visible=False)
ax4.set_title('40 Nodes')
df1 = pd.DataFrame({'Metric':np.random.randint(0, 15, 1000)})
df2 = pd.DataFrame({'Metric':np.random.randint(0, 15, 1000)})
df3 = pd.DataFrame({'Metric':np.random.randint(0, 15, 1000)})
nodes = [10, 20, 30, 40]
for i in range(4):
"""
In my real code, the DataFrames are calculated from reading CSV files.
Since that code would be too long, I'm using dummy data.
"""
plot_data(df1, nodes[i])
# I understand that this calls cause the warning,
# but I don't know how to solve it
plot_data(df2, nodes[i])
plot_data(df3, nodes[i])
plt.show()
【问题讨论】:
-
我真的不明白你为什么要使用多个
ifs 而不是ifelif以及为什么你没有将 axarr 对象从 subplots 传递到函数中(使用节点列表)并在函数中执行循环而不是调用函数 3 次?
标签: python matplotlib