How to create a 3D scatter plot using SciPy (NumPy) and matplotlib in Python. Sample data uses iris.csv (http://aima.cs.berkeley.edu/data/iris.csv)
With the scipy.genformtxt method, you can directly import the data of the csv file in scipy.array format.
Data in scipy.array format can be treated as an ordinary array, and records that meet the conditions can be easily extracted, such as d [d [:, 0]> = 7]. When using multiple conditional expressions, concatenate them with a bit operator.
The scatter3D method can be used when drawing a graph, but it becomes extremely heavy when the number of data is large. The plot method is better. </ del>
(5/9 postscript) In the plot method, the plots are overwritten in the order in which the data is read, so when the plots overlap, the three-dimensional context becomes strange. The scatter method is heavy and difficult to rotate the graph, but the three-dimensional context is more accurate. </ del>
(5/10 postscript) It was the same with scatter that the three-dimensional overlap was strange. It looks like an open issue with matplotlib. If you want to draw a beautiful 3D graph, you can use MayaVi.
http://matplotlib.org/mpl_toolkits/mplot3d/faq.html
You can specify color (marker color), ms (Marker Size, marker size), mew (Marker Edge Width, marker border thickness), etc. as properties of the plot method.
plot3d.py
# coding: UTF-8
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from scipy import genfromtxt
#File reading
d = genfromtxt("./temp/iris.csv", delimiter=",")
#Graph creation
fig = pyplot.figure()
ax = Axes3D(fig)
#Axis label settings
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
#Display range setting
ax.set_xlim(4, 8)
ax.set_ylim(2, 5)
ax.set_zlim(1, 8)
#Extraction condition setting
d1 = d[d[:,0] >= 7]
d2 = d[(d[:,0] < 7) & ((d[:,1] > 3) & (d[:,1] <= 3.5))]
d3 = d[(d[:,0] < 7) & ((d[:,1] <= 3) | (d[:,1] > 3.5))]
#Graph drawing
ax.plot(d1[:,0], d1[:,1], d1[:,2], "o", color="#cccccc", ms=4, mew=0.5)
ax.plot(d2[:,0], d2[:,1], d2[:,2], "o", color="#00cccc", ms=4, mew=0.5)
ax.plot(d3[:,0], d3[:,1], d3[:,2], "o", color="#ff0000", ms=4, mew=0.5)
pyplot.show()
A separate window will open and the graph will be displayed. The graph can be rotated freely by dragging. You can output the following png file with the save icon on the menu bar.
Recommended Posts