我有一組每年安排的坐標,我將它們散點圖。我創建了一個反映那些年的自定義顏色圖,但問題是我無法繪制該顏色圖的顏色條,并用 datetime64 的 numpy 陣列的值替換刻度。我不知道怎么做,因為我沒有繪制任何影像(網上的例子主要是 plt.imshow)。
我怎么能:
- 使用我的自定義顏色圖繪制顏色條
- 用我的日期替換顏色條的刻度?
這是我的代碼:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
# Create the dates
dates = np.datetime64('2017') np.arange(5)*np.timedelta64(1, 'Y')
# Create array where the dates are the 2nd dimension
arr = np.random.randn(3,5,10,2)
colors = cm.seismic(np.linspace(0,1, num=arr.shape[1]))
fig,ax = plt.subplots()
# Iterate through the 1st and 2nd dimension
for g in range(0,arr.shape[0]):
for i in range(0,arr.shape[1]):
plot = plt.scatter(arr[g,i,:,0],arr[g,i,:,1], s = 10, marker = '_', color = colors)
# Attempt to plot the colorbar and replace ticks by the years
cb = plt.colorbar()
loc = mdates.AutoDateLocator()
cb.ax.yaxis.set_major_locator(loc)
cb.ax.yaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
colors
uj5u.com熱心網友回復:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
import numpy as np
# Create the dates
dates = np.datetime64('2017') np.arange(5)*np.timedelta64(1, 'Y')
# Create array where the dates are the 2nd dimension
arr = np.random.randn(3,5,10,2)
values = np.linspace(0,1, num=arr.shape[1])
# create a normalizer
norm = Normalize(vmin=values.min(), vmax=values.max())
# normalize values
norm_values = norm(values)
# choose a colormap
cmap = cm.seismic
# create colors
colors = cmap(norm_values)
# map values to a colorbar
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
mappable.set_array(values)
fig, ax = plt.subplots()
# Iterate through the 1st and 2nd dimension
for g in range(0,arr.shape[0]):
for i in range(0,arr.shape[1]):
plot = plt.scatter(arr[g,i,:,0],arr[g,i,:,1], s = 10, marker = '_', color = colors[i])
# replace ticks by the years
cb = fig.colorbar(mappable, ticks=values)
cb.ax.set_yticklabels(dates)
cb.set_label("Date")

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/468453.html
標籤:Python 约会时间 matplotlib 彩条
