2

我试图通过从多个输入文件中读取多元数据模型来可视化它们。我正在寻找一种简单的解决方案来可视化从多个输入 csv 文件中读取的多个类别数据。没有。单个文件中输入的行数范围从 1 到 10000。具有 4 列 csv 文件的所有输入的格式相同。

输入 1

tweetcricscore 34  51 high

输入 2

tweetcricscore 23 46 low
tweetcricscore 24  12 low
tweetcricscore 456 46 low

输入 3

tweetcricscore 653  1 medium 
tweetcricscore 789 178 medium

输入 4

tweetcricscore 625  46 part
tweetcricscore 86  23 part
tweetcricscore 3  1 part
tweetcricscore 87 8 part
tweetcricscore 98 56 part

这四个输入分别属于不同的类别,col[1]并且col[2]是某种分类的配对结果。这里的所有输入都是同一分类的输出。我想以更好的方式将它们可视化,以便仅在一个图中显示所有类别。寻找相同的python或pandas解决方案。散点图或任何最佳的绘图方法。

我已经在堆栈交换的数据分析部分发布了这个查询,但我没有运气,因此在这里尝试。 https://datascience.stackexchange.com/questions/11440/multi-model-data-set-visualization-python

可能如下图所示,其中每个类都有自己的标记和颜色,并且可以进行分类,或者以任何更好的方式一起显示对值。

代码:编辑 1:我正在尝试使用上述输入文件绘制散点图。

import numpy as np
import matplotlib.pyplot as plt
from pylab import*
import math
from matplotlib.ticker import LogLocator
import pandas as pd

df1 = pd.read_csv('input_1.csv', header = None)

df1.columns = ['col1','col2','col3','col4']
plt.df1(kind='scatter', x='col2', y='col3', s=120, c='b', label='Highly')

plt.legend(loc='upper right')
plt.xlabel('Freq (x)')
plt.ylabel('Freq(y)')
#plt.gca().set_xscale("log")
#plt.gca().set_yscale("log")
plt.show()

错误:

Traceback (most recent call last):
  File "00_scatter_plot.py", line 12, in <module>
    plt.scatter(x='col2', y='col3', s=120, c='b', label='High')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 3087, in scatter
    linewidths=linewidths, verts=verts, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 6337, in scatter
    self.add_collection(collection)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 1481, in add_collection
    self.update_datalim(collection.get_datalim(self.transData))
  File "/usr/lib/pymodules/python2.7/matplotlib/collections.py", line 185, in get_datalim
    offsets = np.asanyarray(offsets, np.float_)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 514, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
ValueError: could not convert string to float: col2

预期输出绘图 - Pandas

散点图

4

4 回答 4

2

更新:

有不同的颜色:

colors = dict(low='DarkBlue', high='red', part='yellow', medium='DarkGreen')

fig, ax = plt.subplots()

for grp, vals in df.groupby('col4'):
    color = colors[grp]
    vals[['col2','col3']].plot.scatter(x='col2', y='col3', ax=ax,
                                       s=120, label=grp, color=color)

PS你必须关心你的所有组(col4) - 在colors字典中定义

在此处输入图像描述

旧答案:

假设您已将文件连接/合并/加入到单个 DF 中,我们可以执行以下操作:

fig, ax = plt.subplots()
[vals[['col2','col3']].plot.scatter(x='col2', y='col3', ax=ax, label=grp)
 for grp, vals in df.groupby('col4')]

在此处输入图像描述

PS 作为家庭作业 - 你可以玩颜色;)

于 2016-05-11T17:51:28.353 回答
2

虽然尝试使用@MaxU 的解决方案,但他的解决方案很棒,但不知何故,我几乎没有错误,并且正在修复错误。我遇到了这个看起来类似于Seaborn的替代Boken我正在共享代码只是作为一些初学者参考的替代。

代码:

import numpy as np
import matplotlib.pyplot as plt
from pylab import*
import math
from matplotlib.ticker import LogLocator
import pandas as pd
from bokeh.charts import Scatter, output_file, show

df = pd.read_csv('input.csv', header = None)

df.columns = ['col1','col2','col3','col4']

scatter = Scatter( df, x='col2', y='col3', color='col4', marker='col4', title='plot', legend=True)

output_file('output.html', title='output')

show(scatter)

输出:

输出

于 2016-05-12T06:25:46.460 回答
1

考虑绘制一个连接多个 .txt 文件的 pandas df 的 pivot_table。下面运行两种类型的带有Type分组和Class2分组的枢轴。差距是由于NaN数据透视:

import pandas as pd
import numpy as np
from matplotlib import rc, pyplot as plt
import seaborn

# IMPORT .TXT DATA
df = pd.concat([pd.read_table('TweetCricScore1.txt', header=None, sep='\\s+'),
                pd.read_table('TweetCricScore2.txt', header=None, sep='\\s+'),
                pd.read_table('TweetCricScore3.txt', header=None, sep='\\s+'),
                pd.read_table('TweetCricScore4.txt', header=None, sep='\\s+')])    
df.columns = ['Class1', 'Class2', 'Score', 'Type']

# PLOT SETTINGS
font = {'family' : 'arial', 'weight' : 'bold', 'size'   : 10}    
rc('font', **font); rc("figure", facecolor="white"); rc('axes', edgecolor='darkgray')

seaborn.set()      # FOR MODERN COLOR DESIGN

def runplot(pvtdf):
    pvtdf.plot(kind='bar', edgecolor='w',figsize=(10,5), width=0.9, fontsize = 10)    
    locs, labels = plt.xticks()
    plt.title('Tweet Cric Score', weight='bold', size=14)
    plt.legend(loc=1, prop={'size':10}, shadow=True)
    plt.xlabel('Classification', weight='bold', size=12)
    plt.ylabel('Score', weight='bold', size=12)
    plt.tick_params(axis='x', bottom='off', top='off')
    plt.tick_params(axis='y', left='off', right='off')
    plt.ylim([0,100])
    plt.grid(b=False)
    plt.setp(labels, rotation=45, rotation_mode="anchor", ha="right")
    plt.tight_layout()

# PIVOT DATA
sumtable = df.pivot_table(values='Score', index=['Class2'],
                          columns=['Type'], aggfunc=sum)
runplot(sumtable)
sumtable = df.pivot_table(values='Score', index=['Type'],
                          columns=['Class2'], aggfunc=sum)
runplot(sumtable)

透视图 图 1 透视图 图 2

于 2016-05-11T03:45:39.813 回答
1

所以首先,在你的绘图代码中。有几个错误,根据您包含的错误,一个看起来只是一个错字。更改您调用的列名称后,plt.df1(...)这应该是plt.scatter(...),并且从您包含的错误中看起来这就是您实际调用的内容。您的错误提醒您的问题是您正在尝试调用 x='col2' ,其中 'col2' 是 matplotlib 想要绘制的值。我意识到您正在尝试从 df1 输入“col2”,但不幸的是这不是您所做的。为此,您只需调用plt.scatter(df1.col2, df1.col3, ...)where df1.col2 和 df1.col3 分别代表您的 x 和 y 值的系列。修复此问题将为您提供以下输出(我使用 input4,因为它具有最多的数据点):

在此处输入图像描述

就在一张图表上绘制多个类别而言,您有多种选择。您可以将绘图代码更改为:

fig, ax = plt.subplots()
ax.plot(df1.col2, df1.col3, 'bo', label='Highly')
ax.plot(df2.col2, df2.col2, 'go', label='Moderately')
ax.legend()
ax.xlabel('Freq (x)')
ax.ylabel('Freq(y)')
plt.show()

然而,这相当笨拙。最好将所有数据放在一个数据框中,并添加一个标题为标签的列,该列根据您对数据的分类方式获取您想要的标签值。这样你就可以使用类似的东西:

fig, ax = plt.subplots()
for group, name in df.groupby('label'):
    ax.plot(group.x, group.y, marker='o', label=name)
ax.legend()
plt.show()
于 2016-05-11T17:54:45.223 回答