matplotlib plotting multiple lines in 3D

你。 提交于 2021-01-27 07:07:32

问题


I am trying to plot multiple lines in a 3D plot using matplotlib. I have 6 datasets with x and y values. What I've tried so far was, to give each point in the data sets a z-value. So all points in data set 1 have z=1 all points of data set 2 have z=2 and so on. Then I exported them into three files. "X.txt" containing all x-values, "Y.txt" containing all y-values, same for "Z.txt".

Here's the code so far:

        #!/usr/bin/python
        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        import numpy as np
        import pylab

        xdata = '/X.txt'
        ydata = '/Y.txt'
        zdata = '/Z.txt'

        X = np.loadtxt(xdata)
        Y = np.loadtxt(ydata)
        Z = np.loadtxt(zdata)

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_wireframe(X,Y,Z)
        plt.show()

What I get looks pretty close to what I need. But when using wireframe, the first point and the last point of each dataset are connected. How can I change the colour of the line for each data set and how can I remove the connecting lines between the datasets?

Is there a better plotting style then wireframe?


回答1:


Load the data sets individually, and then plot each one individually.

I don't know what formats you have, but you want something like this

from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

datasets = [{"x":[1,2,3], "y":[1,4,9], "z":[0,0,0], "colour": "red"} for _ in range(6)]

for dataset in datasets:
    ax.plot(dataset["x"], dataset["y"], dataset["z"], color=dataset["colour"])

plt.show()

Each time you call plot (or plot_wireframe but i don't know what you need that) on an axes object, it will add the data as a new series. If you leave out the color argument matplotlib will choose them for you, but it's not too smart and after you add too many series' it will loop around and start using the same colours again.

n.b. i haven't tested this - can't remember if color is the correct argument. Pretty sure it is though.



来源:https://stackoverflow.com/questions/19679019/matplotlib-plotting-multiple-lines-in-3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!