多输入多元数据可视化
Multiple inputs multivariate data visualisation
我正在尝试通过从多个输入文件中读取多变量数据模型来可视化它们。我正在寻找一种简单的解决方案来可视化从多个输入 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]
是某种 class 化的成对结果。这里的所有输入都是同一个 classification 的输出。我想以更好的方式将它们可视化,以仅在一个图中显示所有类别。寻找相同的 python 或 pandas 解决方案。散点图或任何最佳绘图方法。
我已经在 stack exchange 的数据分析部分发布了这个查询,但我运气不好,因此在这里尝试。
https://datascience.stackexchange.com/questions/11440/multi-model-data-set-visualization-python
可能类似于下图,其中每个 class 都有自己的标记和颜色,可以分类或以任何更好的方式一起显示对值。
代码:编辑 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
预期输出Plotting- Pandas
考虑绘制 pivot_table 的 pandas df,它连接了许多 .txt 文件。下面使用 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)
更新:
不同颜色:
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
字典
中定义
旧答案:
假设您已 concatenated/merged/joined 将文件放入单个 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 作为作业 - 你可以玩颜色 ;)
首先,在您的绘图代码中。有几个错误,根据您包含的错误,其中一个看起来像是拼写错误。更改列名后,您调用 plt.df1(...)
这应该是 plt.scatter(...)
并且从您包含的错误来看,它看起来像是您实际调用的内容。您的错误提醒您的问题是您正在尝试调用 x='col2' 并且 'col2' 是 matplotlib 想要绘制的值。我知道您正在尝试从 df1 输入 'col2' 但不幸的是您没有这样做。为此,您只需调用 plt.scatter(df1.col2, df1.col3, ...)
,其中 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()
虽然尝试使用@MaxU 的解决方案,但他的解决方案很棒,但不知何故我几乎没有错误,并且正在修补错误。我遇到了这个替代方案 Boken which looks similar to Seaborn 我分享代码只是作为一些初学者参考的替代方案。
代码:
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)
输出:
我正在尝试通过从多个输入文件中读取多变量数据模型来可视化它们。我正在寻找一种简单的解决方案来可视化从多个输入 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]
是某种 class 化的成对结果。这里的所有输入都是同一个 classification 的输出。我想以更好的方式将它们可视化,以仅在一个图中显示所有类别。寻找相同的 python 或 pandas 解决方案。散点图或任何最佳绘图方法。
我已经在 stack exchange 的数据分析部分发布了这个查询,但我运气不好,因此在这里尝试。 https://datascience.stackexchange.com/questions/11440/multi-model-data-set-visualization-python
可能类似于下图,其中每个 class 都有自己的标记和颜色,可以分类或以任何更好的方式一起显示对值。
代码:编辑 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
预期输出Plotting- Pandas
考虑绘制 pivot_table 的 pandas df,它连接了许多 .txt 文件。下面使用 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)
更新:
不同颜色:
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
字典
旧答案:
假设您已 concatenated/merged/joined 将文件放入单个 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 作为作业 - 你可以玩颜色 ;)
首先,在您的绘图代码中。有几个错误,根据您包含的错误,其中一个看起来像是拼写错误。更改列名后,您调用 plt.df1(...)
这应该是 plt.scatter(...)
并且从您包含的错误来看,它看起来像是您实际调用的内容。您的错误提醒您的问题是您正在尝试调用 x='col2' 并且 'col2' 是 matplotlib 想要绘制的值。我知道您正在尝试从 df1 输入 'col2' 但不幸的是您没有这样做。为此,您只需调用 plt.scatter(df1.col2, df1.col3, ...)
,其中 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()
虽然尝试使用@MaxU 的解决方案,但他的解决方案很棒,但不知何故我几乎没有错误,并且正在修补错误。我遇到了这个替代方案 Boken which looks similar to Seaborn 我分享代码只是作为一些初学者参考的替代方案。
代码:
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)
输出: