【问题标题】:How can I create more colors for my plot?如何为我的绘图创建更多颜色?
【发布时间】:2020-12-17 20:18:25
【问题描述】:

我试图在 matplotlib 中使用 pyplot 绘制具有 12 条不同线条的绘图,但是似乎只有 10 种不同的颜色导致其中两种颜色重复。我尝试使用 plt.set_cmap('Set3') 来获得更多可用颜色,但没有任何改变。我该怎么办?我对编程还很陌生,所以我可能会遗漏一些我还没有学到的东西。

这是我正在使用的代码

import netCDF4 as nd
import matplotlib.pyplot as plt

data = []
for k in range(1,13):
    nc_file = f'./MIMOC/MIMOC_ML_v2.2_CT_SA_MLP_month{k:02d}.nc'
    with nc.Dataset(nc_file) as nc_fid:
        lat = nc_fid['LATITUDE'][:]
        lon = nc_fid['LONGITUDE'][:]
        temp = nc_fid['CONSERVATIVE_TEMPERATURE_MIXED_LAYER'][:,:]
    data.append(temp)
    
months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

for i in data:

    plt.plot(lat, i[:,660], label = months)

plt.legend(months, loc = 'right', bbox_to_anchor=(1.53,0.83), ncol=2)
plt.xlabel('latitude')
plt.ylabel('temperature [degC]')
plt.title('Monthly surface temperature along 30W')
plt.show()

【问题讨论】:

  • 我主要想知道的是如何更改此图的颜色图以包含更多颜色 plt.plot(lat, i[:,660], label = months)

标签: python matplotlib plot jupyter-notebook


【解决方案1】:

您要设置颜色循环,而不是plt.set_cmap(设置用于图像的颜色映射https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.set_cmap.html?highlight=set_cmap

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from cycler import cycler

cm = plt.get_cmap('Set3')


# you can also set line style, width
matplotlib.rcParams["axes.prop_cycle"] = cycler(
    color=[cm(v) for v in np.linspace(0, 1, 12)]
)

x = np.arange(5)

fig, ax = plt.subplots(constrained_layout=True)
for j in range(24):
    ax.plot(x, x + j, label=f'line {j}')

ax.legend(ncol=2)
plt.show()

但是,如果您已经在循环数据,您最好直接设置颜色而不是依赖prop_cyle(特别是如果您想对要保留的不同轴进行多次绘图调用同步)。

https://matplotlib.org/3.3.3/tutorials/introductory/customizing.html#dynamic-rc-settings

https://matplotlib.org/3.3.3/gallery/color/color_cycle_default.html

https://matplotlib.org/cycler/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2021-06-14
    • 2023-03-18
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多