【问题标题】:using matplotlib visualize two pandas dataframes in a single scatter plot使用 matplotlib 在单个散点图中可视化两个 pandas 数据帧
【发布时间】:2018-02-08 06:43:34
【问题描述】:

我有两个具有相同列名的 pandas 数据框。

数据框 1:

数据框 2:

  1. 两个数据框具有相同的列名。我需要可视化 两个 dfs 在同一个散点图中,其中 X 轴是值 出现在“功能”列中,即 D1_1_2、D1_2_3 等
  2. 所有条目(或标签)都需要单个散点图,例如: 'D1_1_2'、'D1_2_3' 等,在 'function' 列中作为 X 轴。 Y 轴可以动态选取数值。
  3. 两个数据框值的颜色不同。
  4. 在重叠值之间添加间距或抖动。

在这方面需要支持。

【问题讨论】:

  • 您期望 y 轴上的哪个变量?您能否显示原始数据的预期输出?
  • 我已经添加了预期输出的图像,Y 轴将具有动态数值。例如:基于输入数据 D1_1_2 标签的值将显示为 Y 轴上显示的 39736、0.0 1.37 等。

标签: python pandas matplotlib


【解决方案1】:

通过以下示例,您可能会了解如何做您正在寻找的东西:

import pandas as pd
import matplotlib.pyplot as plt
index = ["D1_1-2", "D1_2-3", "D1_3-4"]
df1 = pd.DataFrame({"count": [10, 20, 25]}, index=index)
df2 = pd.DataFrame({"count": [15, 11, 30]}, index=index)
ax = df1.plot(style='ro', legend=False)
df2.plot(style='bo',ax=ax, legend=False)
plt.show()

关键是要求df2 的绘图使用df1 绘图的轴。

你得到的情节如下:

有抖动的方法:

如果您想为数据添加抖动,一种方法可以如下所示,我们不使用先前的绘图轴,而是连接数据帧并对其进行迭代:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
index = ["D1_1-2", "D1_2-3", "D1_3-4", "D1_4-5", "D1_5-6", "D1_6-7", "D1_7-8", "D1_8-9", "D1_1-3", "D1_2-3", "D1_3-5", "D1_5-7"]
df1 = pd.DataFrame({"count": [10, 20, 25, 30, 32, 35, 25, 15, 5, 17, 11, 2]}, index=index)
df2 = pd.DataFrame({"count": [15, 11, 30, 30, 20, 30, 25, 27, 5, 16, 11, 5]}, index=index)

#We ensure we use different column names for df1 and df2
df1.columns = ["count1"]
df2.columns = ["count2"]

#We concatenate the dataframes
df = pd.concat([df1, df2],axis=1)

#Function to add jitter to the array
def rand_jitter(arr):
    stdev = .01*(max(arr)-min(arr))
    return arr + np.random.randn(len(arr)) * stdev

# We iterate between the two columns of the concatenated dataframe
for i,d in enumerate(df):
    y = df[d]
    arr = range(1,len(y)+1)
    x = rand_jitter(arr)
    plt.plot(x, y, mfc = ["red","blue"][i], mec='k', ms=7, marker="o", linestyle="None")

# We set the ticks as the index labels and rotate the labels to avoid overlapping
plt.xticks(arr, index, rotation='vertical')
plt.show()

最终结果如下图:

【讨论】:

  • 谢谢@cedric,这段代码很有帮助,但是我面临的问题很少。 1. 当我在 X 轴上包含大约 40 个索引(或标签)时,其中很多都没有显示。那么如何在 X 轴上显示所有索引。 2.两个数据帧上的许多对应值都重叠,如何在重叠值之间添加一些间距(或抖动)。
  • 您是否可以提供您正在使用的实际数据的链接?
  • @GyanendraVerma 请查看更新后的答案,并在图表中添加了抖动。
  • @GyanendraVerma 的答案很有帮助,是您所期望的吗?如果是这样,请考虑投票和/或标记为已接受;)
  • 对不起,我被其他任务卡住了,所以之前无法检查...我现在检查了它,它对我有用..谢谢您的帮助...再次抱歉迟到了在回复中。
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
相关资源
最近更新 更多