【问题标题】:How to create a scatter plot where values are across multiple columns?如何创建值跨多列的散点图?
【发布时间】:2019-06-08 12:18:48
【问题描述】:

我在 Pandas 中有一个数据框,其中的行是不同时间的观察结果,每列是一个尺寸箱,其中的值表示针对该尺寸箱观察到的粒子数。所以它看起来像下面这样:

         bin1    bin2    bin3    bin4    bin5
Time1    50      200     30      40      5

Time2    60      60      40      420     700

Time3    34      200     30      67      43

我想使用 plotly/cufflinks 创建一个散点图,其中 x 轴将是每个尺寸箱,y 轴将是每个尺寸箱中的值。将有三种颜色,每种观察一种颜色。

由于我在 Matlab 中的经验更丰富,我尝试使用 iloc 对值进行索引(注意下面的示例只是试图绘制一个观察结果):

df.iplot(kind="scatter",theme="white",x=df.columns, y=df.iloc[1,:])

但我只收到一个关键错误:0 条消息。

在 Pandas 中选择 x 和 y 值时是否可以使用索引?

【问题讨论】:

    标签: python-3.x pandas plotly-python


    【解决方案1】:

    我认为您需要更好地了解pandasmatplotlib 之间的交互方式,而不是索引。

    让我们为您的案例分步进行:

    1. 正如pandas.DataFrame.plot 文档所说,绘制的系列是一列。您在行中有系列,因此您需要转置您的数据框。

    2. 要创建散点图,您需要在不同的列中同时拥有 x 和 y 坐标,但是您缺少 x 列,因此您还需要在转置后的数据框中创建一个包含 x 值的列。

    3. 显然pandas 在连续调用plot 时默认不会改变颜色(matplotlib 会这样做),所以你需要选择一个颜色图并传递一个颜色参数,否则所有点都会有一样的颜色。

    这是一个工作示例:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    #Here I copied you data in a data.txt text file and import it in pandas as a csv.
    #You may have a different way to get your data.
    df = pd.read_csv('data.txt', sep='\s+', engine='python')
    
    #I assume to have a column named 'time' which is set as the index, as you show in your post.
    df.set_index('time')
    
    tdf = df.transpose() #transpose the dataframe
    
    #Drop the time column from the trasponsed dataframe. time is not a data to be plotted.
    tdf = tdf.drop('time')
    
    #Creating x values, I go for 1 to 5 but they can be different.
    tdf['xval'] = np.arange(1, len(tdf)+1)
    
    #Choose a colormap and making a list of colors to be used.
    colormap = plt.cm.rainbow
    colors = [colormap(i) for i in np.linspace(0, 1, len(tdf))]
    
    #Make an empty plot, the columns will be added to the axes in the loop.
    fig, axes = plt.subplots(1, 1)
    for i, cl in enumerate([datacol for datacol in tdf.columns if datacol != 'xval']):
        tdf.plot(x='xval', y=cl, kind="scatter", ax=axes, color=colors[i])
    
    plt.show()
    

    这绘制了以下图像:

    Here 在 matplotlib 中挑选颜色的教程。

    【讨论】:

    • 谢谢。在解决这个问题后不久,我意识到解决方案的核心在于转置数据帧。再次感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多