2017-08-30 51 views
-3

我有两个具有相同列名称的熊猫数据帧。使用matplotlib在单个散点图中可视化两个熊猫数据帧

数据帧1:

Dataframe 1

数据帧2:

Dataframe 2

  1. 这两个数据帧具有相同的列名。我需要在相同散点图中显示 这两个dfs,其中X轴将是'函数'列中存在的值 ,即D1_1_2,D1_2_3等
  2. 单个散点图对于所有条目(或标签) 'D1_1_2','D1_2_3'等,在'function'列中作为X轴。 Y轴可以动态选取数值。
  3. 两种数据帧值都有不同的颜色。
  4. 在重叠值之间添加间距或抖动。

在此需要支持。

Expected output:

+0

您期望在y轴中使用哪个变量?你能否显示你原始数据的预期输出? –

+0

我添加了期望输出的图像,Y轴将具有动态数值。例如:基于输入数据D1_1_2,标签的值将显示为39736,0.0 1.37等,显示在Y轴上。 –

回答

0

有了下面的例子,你可能会得到关于如何做你正在寻找一个想法:

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情节使用的轴。

你得到这个情节如下: enter image description here

阿布罗奇抖动:

如果你想抖动添加到您的数据的一种方法可以如下,其中,而不是使用前面的情节轴线串连我们的dataframes和遍历它:

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() 

最后这个结果对下图: enter image description here

+0

谢谢@cedric这段代码很有帮助,但是我面临的问题很少。 1.当我在X轴上包含大约40个索引(或标签)时,其中很多都没有显示。那么我如何显示X轴上的所有索引。 2.两个数据帧上的许多对应值都是重叠的,我如何在重叠值之间添加一些间距(或抖动)。 –

+0

您是否可以提供与正在使用的实际数据的链接? –

+0

@GyanendraVerma请参阅添加到图形中的抖动更新答案。 –