matplotlib 按3D散点图中点的日期添加颜色条

omjgkv6w  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(123)

我试图在3D图中绘制某个地区的地震,用颜色来显示事件的时间/日期。数据点的颜色是准确的,但是,当我绘制颜色条时,它只显示0.0到1.0。如何让颜色条显示日期作为其标签?
我的dates变量是“YYYY-MM-DD”格式的日期列表。

%matplotlib notebook
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(projection='3d')

ax.scatter(longitude, latitude, -depth, c=mdates.date2num(dates), cmap='magma')
fig.colorbar(mpl.cm.ScalarMappable(cmap='magma'))
plt.show()
dpiehjr4

dpiehjr41#

因为你没有提供数据,我只能随机生成。

from mpl_toolkits.mplot3d import axes3d
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.colors import Normalize
import numpy as np

# generate random data and dates
longitude = np.random.uniform(0, 1, 100)
latitude = np.random.uniform(0, 1, 100)
depth = np.random.uniform(0, 1, 100)

dates = []
for i in range(1, 13):
    for j in range(1, 25):
        if j < 10: n = "0" + str(j)
        else: n = j
        if i < 10: m = "0" + str(i)
        else: n = i
        dates.append("2022-{}-{}".format(m, n))

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(projection='3d')

colors = mdates.date2num(dates[:100])
ax.scatter(longitude, latitude, -depth, c=colors, cmap='magma')
norm = Normalize(vmin=colors.min(), vmax=colors.max())

# choose a proper number of ticks to be shown on the colorbar
N = 5
ticks = np.linspace(colors.min(), colors.max(), N)
# convert the tick back to date format
labels = [mdates.num2date(t).strftime("%Y-%m-%d") for t in ticks]
cb = fig.colorbar(
    mpl.cm.ScalarMappable(norm=norm, cmap='magma'),
    ticks=ticks,
    ax=ax,
    label="Date"
)
cb.ax.set_yticklabels(labels)
plt.show()

相关问题