【问题标题】:3D chart with XY string in PandasPandas 中带有 XY 字符串的 3D 图表
【发布时间】:2019-07-29 07:39:27
【问题描述】:

我有一个来自 CSV 数据(矩阵)的dataframe,如下所示:

    BS1 BS2 BS3 BS4 BS5 BS6 BS7 BS8 BS9
BS1 0   1   6   1   0   0   0   0   0
BS2 1   0   8   1   0   0   0   0   0
BS3 0   6   0   2   3   1   0   0   0
BS4 0   0   4   0   1   2   0   0   0
BS5 0   1   3   2   0   3   0   0   0
BS6 0   0   0   0   0   0   5   4   2
BS7 0   4   7   3   4   0   0   5   6
BS8 0   0   0   0   0   0   5   0   7
BS9 0   1   5   0   1   0   4   0   0

我想根据这个 CSV 矩阵数据制作一个 3D 图表。但是,XY 是字符串。怎么做?

预期的结果看起来像这个链接3D Scatterplot with strings in Python

谢谢。

【问题讨论】:

  • XY 长什么样子?您可能正在查看numpy 广播

标签: python pandas


【解决方案1】:

对于要绘制的每个值,scatter 函数需要 x、y 和 z 值。 试试这个:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Assuming data is imported as pandas dataframe
io = StringIO('''    BS1 BS2 BS3 BS4 BS5 BS6 BS7 BS8 BS9
BS1 0   1   6   1   0   0   0   0   0
BS2 1   0   8   1   0   0   0   0   0
BS3 0   6   0   2   3   1   0   0   0
BS4 0   0   4   0   1   2   0   0   0
BS5 0   1   3   2   0   3   0   0   0
BS6 0   0   0   0   0   0   5   4   2
BS7 0   4   7   3   4   0   0   5   6
BS8 0   0   0   0   0   0   5   0   7
BS9 0   1   5   0   1   0   4   0   0''')
df = pd.read_csv(io, sep='\s+')

# Get columns, rows and values from dataframe
xs = df.columns
ys = df.index
zs = df.values

# Prepare coordinates
x = np.linspace(0, len(xs) - 1, len(xs))
y = np.linspace(0, len(ys) - 1, len(ys))
xv, yv = np.meshgrid(x,y)

ax.scatter(xv, yv, zs)
ax.set(xticks=range(len(xs)), xticklabels=xs,
        yticks=range(len(ys)), yticklabels=ys) 

【讨论】:

  • 这不是硬编码轴吗?
  • 是否可以使用csv数据?因为我有很多CSV矩阵数据,,,
  • @WolfgangK 我收到了这条消息could not convert string to float:
  • @WolfgangK 错误在这部分zs = np.loadtxt('data.csv', delimiter=',')
  • @Arief 如何使用分类/字符串 XY 轴标签创建 3D 散点图的主要问题已在答案的第一次迭代中得到解决。之后在 cmets 中出现的后续问题特定于您的文件和格式化需求,并且 imo 不应该是答案的一部分,因为这些问题也没有反映在问题中。如果您需要有关这些主题的帮助,我建议您首先给出完整的问题描述或打开一个新问题。
猜你喜欢
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 2021-12-01
  • 2020-06-27
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多