【问题标题】:Scatter plotting data from two different data frames in pythonpython中两个不同数据帧的散点图数据
【发布时间】:2018-03-03 10:46:04
【问题描述】:

我有两个不同的数据框,格式如下。

dfclean
Out[1]: 
      obj
0     682
1     101
2      33

dfmalicious
Out[2]: 
                obj
        0        17
        1        43
        2         8
        3         9
        4       211

我的用例是绘制一个散点图,清楚地显示两个数据帧中的obj 值。我为此目的使用python。我查看了一些示例,其中两列相同的数据框用于绘制数据,但无法为我的用例复制它。任何帮助是极大的赞赏。

How to plot two DataFrame on same graph for comparison

【问题讨论】:

  • 你需要将你的两个数据框变成一个数据框,然后你可以使用你已经找到的绘图提示。因此,您的问题实际上是关于加入/合并数据框。关于 SO re: merging dataframes in pandas 已经有很多问题了
  • @PaulH 谢谢。我能够连接两个数据框并能够创建一个图。我的下一个挑战是缩小我的轴。你能帮我看看如何缩放我的 y 轴以显示 1 到 1000 之间的数据吗?
  • 关于为 matplotlib 图设置轴限制的问题可能有几十个。浏览其中的几个,以及 matplotlib+pandas 文档,告诉我你觉得困惑的地方。

标签: python pandas matplotlib dataframe plot


【解决方案1】:

要在单个轴上绘制多个列组,请重复 plot 方法指定目标 ax

选项 1]

In [2391]: ax = dfclean.reset_index().plot(kind='scatter', x='index', y='obj',
                                           color='Red', label='G1')

In [2392]: dfmalicious.reset_index().plot(kind='scatter', x='index', y='obj',
                                          color='Blue', label='G2', ax=ax)
Out[2392]: <matplotlib.axes._subplots.AxesSubplot at 0x2284e7b8>

选项 2]

In [2399]: dff = dfmalicious.merge(dfclean, right_index=True, left_index=True,
                                   how='outer').reset_index()

In [2406]: dff
Out[2406]:
   index  obj_x  obj_y
0      0     17  682.0
1      1     43  101.0
2      2      8   33.0
3      3      9    NaN
4      4    211    NaN

In [2400]: ax = dff.plot(kind='scatter', x='index', y='obj_x', color='Red', label='G1')

In [2401]: dff.plot(kind='scatter', x='index', y='obj_y', color='Blue', label='G2', ax=ax)
Out[2401]: <matplotlib.axes._subplots.AxesSubplot at 0x11dbe1d0>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多