带XY字符串的三维图表

2024-10-01 19:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个来自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

谢谢你。你知道吗


Tags: csv数据dataframe图表矩阵xybs4bs3
1条回答
网友
1楼 · 发布于 2024-10-01 19:34:13

对于要绘制的每个值,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) 

相关问题 更多 >

    热门问题