Matplotlib 如何从图中获取XY数据
在数据可视化中,Matplotlib是Python中使用最广泛的绘图库之一。我们通常使用Matplotlib来绘制数据图形,掌握如何从Matplotlib图形中检索XY数据是非常重要的。
阅读更多:Matplotlib 教程
Matplotlib中基础图形的XY数据
在Matplotlib中,我们可以通过以下三种方法创建基本图形:使用plot方法创建线图、使用scatter方法创建散点图、使用hist方法创建直方图。我们可以使用以下方法检索这些图形中的XY数据。
- Plot
通过以下方法,可以从线图中检索出所有的XY数据:
import matplotlib.pyplot as plt
# 生成x、y数据
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
# 绘制线图
plt.plot(x, y)
# 检索X和Y数据
xy_data = plt.gca().lines[0].get_xydata()
print(xy_data)
这里使用了plt.gca()方法获取当前的Axes对象,然后使用lines[0]获得第一根线的对象,最后使用get_xydata()获得该线的XY数据。
- Scatter
对于散点图,可以使用以下方法获得所有的XY数据:
import matplotlib.pyplot as plt
# 生成x、y数据
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
# 绘制散点图
plt.scatter(x, y)
# 检索X和Y数据
xy_data = plt.gca().collections[0].get_offsets()
print(xy_data)
这里使用了collections[0]获得第一个Collection对象,然后使用get_offsets()方法检索出所有的XY数据。
- Hist
对于直方图,可以使用以下方法获得所有的XY数据:
import matplotlib.pyplot as plt
import numpy as np
# 生成1000个随机数
data = np.random.randn(1000)
# 绘制直方图
plt.hist(data)
# 检索X和Y数据
xy_data = []
for bar in plt.gca().patches:
xy_data.append((bar.get_x(), bar.get_height()))
print(xy_data)
这里使用了plt.gca().patches获得所有的patches对象,并遍历这些对象。对于每一个对象,可以使用get_x()和get_height()方法获取X和Y数据。
以上三种方法都返回一个包含XY数据的二维数组。
从Matplotlib Subplot中检索XY数据
除了基础图形之外,我们还可以使用subplots创建多个图形。这时我们需要使用以下方法检索每个子图中的XY数据。
import matplotlib.pyplot as plt
# 生成x、y数据
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
# 创建2x2的图形
fig, axs = plt.subplots(2, 2)
# 绘制线图
axs[0, 0].plot(x, y)
# 绘制散点图
axs[0, 1].scatter(x, y)
# 绘制直方图
axs[1, 0].hist(y)
# 检索所有子图中的XY数据
xy_data = []
for ax in axs.reshape(-1):
for line in ax.lines:
xy_data.append((line.get_xdata(), line.get_ydata()))
for collection in ax.collections:
xy_data.append(collection.get_offsets())
for bar in ax.patches:
xy_data.append((bar.get_x(), bar.get_height()))
print(xy_data)
这里的axs.reshape(-1)将数组展平为一维数组,这样就可以遍历所有的子图。对于每一个子图,可以使用前文介绍的方法获得其中所有的XY数据。
从Matplotlib Figure中检索XY数据
使用plt.subplots创建图形时,plt会自动创建一个Figure对象。我们也可以手动创建Figure对象。在这种情况下,我们需要使用以下方法检索Figure对象中的所有XY数据:
import matplotlib.pyplot as plt
# 生成x、y数据
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
# 创建Figure对象
fig = plt.figure()
# 创建子图并绘制线图
ax = fig.add_subplot(111)
ax.plot(x, y)
# 检索Figure中所有子图的XY数据
xy_data = []
for ax in fig.get_axes():
for line in ax.lines:
xy_data.append((line.get_xdata(), line.get_ydata()))
for collection in ax.collections:
xy_data.append(collection.get_offsets())
for bar in ax.patches:
xy_data.append((bar.get_x(), bar.get_height()))
print(xy_data)
这里使用了fig.get_axes()方法获得Figure中所有的Axes对象,并遍历每个Axes对象,获取其中所有的XY数据。
总结
Matplotlib是一个非常强大和灵活的数据可视化库,掌握如何从Matplotlib图形中检索XY数据是非常有用和基础的技能。本文介绍了从基础图形、Subplot和Figure中检索XY数据的方法,并给出了相应的代码示例。希望本文能够对读者们有所帮助。