简体   繁体   English

在 matplotlib 中过度绘制线条的绘图网格

[英]Grid of plots with lines overplotted in matplotlib

I have a dataframe that consists of a bunch of x,y data that I'd like to see in scatter form along with a line.我有一个 dataframe ,它由一堆 x,y 数据组成,我想以散布形式看到这些数据和一条线。 The dataframe consists of data with its form repeated over multiple categories. dataframe 包含在多个类别中重复其形式的数据。 The end result I'd like to see is some kind of grid of the plots, but I'm not totally sure how matplotlib handles multiple subplots of overplotted data.我想看到的最终结果是某种图的网格,但我不完全确定 matplotlib 如何处理重叠数据的多个子图。

Here's an example of the kind of data I'm working with:这是我正在使用的数据类型的示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

category = np.arange(1,10)

total_data = pd.DataFrame()

for i in category:
    x = np.arange(0,100)
    y = 2*x + 10
    data = np.random.normal(0,1,100) * y
    dataframe = pd.DataFrame({'x':x, 'y':y, 'data':data, 'category':i})

    total_data = total_data.append(dataframe)

We have x data, we have y data which is a linear model of some kind of generated dataset (the data variable).我们有 x 数据,我们有 y 数据,它是某种生成数据集(数据变量)的线性 model。

I had been able to generate individual plots based on subsetting the master dataset, but I'd like to see them all side-by-side in a 3x3 grid in this case.我已经能够基于子集主数据集生成单独的图,但在这种情况下,我希望在 3x3 网格中并排查看它们。 However, calling the plots within the loop just overplots them all onto one single image.然而,在循环中调用这些图只是将它们全部叠加到一个图像上。

Is there a good way to take the following code block and make a grid out of the category subsets?有没有一种很好的方法来获取以下代码块并从类别子集中制作一个网格? Am I overcomplicating it by doing the subset within the plot call?我是否通过在 plot 调用中执行子集来使其过于复杂?

plt.scatter(total_data['x'][total_data['category']==1], total_data['data'][total_data['category']==1])
plt.plot(total_data['x'][total_data['category']==1], total_data['y'][total_data['category']==1], linewidth=4, color='black')

If there's a simpler way to generate the by-category scatter plus line, I'm all for it.如果有更简单的方法来生成按类别分散加线,我完全赞成。 I don't know if seaborn has a similar or more intuitive method to use than pyplot.我不知道 seaborn 是否有比 pyplot 类似或更直观的使用方法。

You can use either sns.FacetGrid or manual plt.plot .您可以使用sns.FacetGrid或手动plt.plot For example:例如:

g = sns.FacetGrid(data=total_data, col='category', col_wrap=3)
g = g.map(plt.scatter, 'x','data')
g = g.map(plt.plot,'x','y', color='k');

Gives:给出:

在此处输入图像描述

Or manual plt with groupby :或使用groupby手动plt

fig, axes = plt.subplots(3,3)

for (cat, data), ax in zip(total_data.groupby('category'), axes.ravel()):
    ax.scatter(data['x'], data['data'])
    ax.plot(data['x'], data['y'], color='k')

gives:给出:

在此处输入图像描述

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

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