简体   繁体   English

Matplotlib。 在'for loops'中绘制到同一轴

[英]Matplotlib. Plotting in 'for loops' to same axis

I have a rather simple problem but something that's had me stumped for 2days. 我有一个相当简单的问题,但有些事情让我难以忍受2天。 I need to plot 2+ files. 我需要绘制2个以上的文件。 Each file will need to be plotted on a total of 25 plots but must be plotted on the same set of axes. 每个文件需要在总共25个图上绘制,但必须绘制在同一组轴上。 (ie. if theres 2 files I need 25 plots with 2 lines on each plot). (即如果我需要2个文件,每个图上需要25个图,每行2行)。

I have this sudo code which generates 50 plots (One line for each)...which is wrong 我有这个sudo代码生成50个图(每行一行)......这是错误的

with open(bamlist, 'r') as bamlist:
    for bam in bamlist:     #Opens the 2 files
        'Generate data Here'
        dataframe = []
        for line in data:
            line = line.split("\t")
            dataframe.append(line[0:4:1])
        df = pd.DataFrame(dataframe, columns=['Chromosome', 'Position', 'N', 'BaseCount'])

        grouped_df = df.groupby('Chromosome')     #groups dataframe into the required 25plots
        for df in grouped_df:
            density_data = 'Get density data from df'
            f, ax = plt.subplots()          
            sns.kdeplot(density_data, ax=ax, linewidth=1)
            pp.savefig()
pp.close()

Is there a way to revert back to the initial set of axis the 2nd time the for loop is entered so that I will get 2 lines per plot with 25plots (as opposed to 50)? 有没有办法在第二次输入for循环时恢复到初始轴的设置,这样我每个绘图就会得到2行25个点(而不是50个)?

Your problem stems from your use of: 您的问题源于您使用:

f, ax = plt.subplots()

This means that you generate a new subplot every time you hit that line (in your case, 50 times). 这意味着每次点击该行时都会生成一个新的子图(在您的情况下为50次)。 You need to generate 25 subplots and reference them later on. 您需要生成25个子图并稍后引用它们。 You can do something like: 你可以这样做:

axes = []
for i in range(25):
    f,ax = plt.subplots()
    axes.append(ax)

Then in your loop: 然后在你的循环中:

for df_index in range(len(grouped_df)):
    df = grouped_df[df_index]
    density_data = 'Get density data from df'
    sns.kdeplot(density_data, ax=axes[df_index], linewidth=1)

You can also do a check to see if the axis doesn't exist (if it extends to more than 25 subplots or something), and if not, create it. 您还可以检查轴是否不存在(如果它扩展到超过25个子图或其他),如果不存在,则创建它。

Using plt.figure() also gets the job done... 使用plt.figure()也可以完成工作......

iterate = -1
for df in grouped_df:
    iterate += 1
    plt.figure(iterate)
    density_data = 'Get density data from df'
    sns.kdeplot(density_data, linewidth=1)
    pp.savefig()
pp.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM