【问题标题】:change color for first level of contourf更改第一级轮廓的颜色
【发布时间】:2016-08-12 12:44:40
【问题描述】:

我正在使用这个脚本来绘制一个拉马钱德兰图(这种图在这里并不重要,重要的是输出的图):

#!/usr/bin/python
# coding: utf-8

"""
Script to plot a heat map of the dihedral angles
http://stackoverflow.com/questions/26351621/turn-hist2d-output-into-contours-in-matplotlib
"""

import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# print(sys.argv[1])

frame, x, y = np.loadtxt(sys.argv[1], unpack=True)

fig = plt.figure(1)
ax = plt.subplot(111)


counts, ybins, xbins, image = plt.hist2d(x, y, bins=180, norm=LogNorm())
plt.clf()
plt.contourf(counts.transpose(), 10, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])

plt.colorbar()

fig.set_size_inches(30, 20)
plt.savefig(sys.argv[1], bbox_inches='tight')

这是我得到的:

这几乎就是我想要的。我希望以最深紫色显示的第一个级别(颜色条上的 0-15)在图表上显示为白色。

可以吗?

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    如果所有 15 岁以下的东西都是白色的,那么面具会起作用吗?

    from numpy import ma
    counts_masked = ma.masked_where(counts<15, counts)
    plt.contourf(counts_masked.transpose(), 10, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])
    

    或者,另一种选择可能是:

    levels = np.linspace(15,165,10) # your colorbar range, starting at 15
    cmap = plt.get_cmap()
    cmap.set_under(color='white')
    plt.contourf(counts.transpose(), levels=levels, cmap=cmap, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])
    

    【讨论】:

      【解决方案2】:

      我实际上在一小时前找到了答案,基于这个问题: Python matplotlib change default color for values exceeding colorbar range

      我只是想反其道而行之,所以我用下面的代码设置了下限:

      cs = plt.contourf(counts.transpose(), 10, extent=[xbins.min(), xbins.max(),
                                                        ybins.min(), ybins.max()])
      
      # All bims under 15 are plotted white
      cs.cmap.set_under('w')
      cs.set_clim(15)
      
      cbar = plt.colorbar(cs)
      

      【讨论】:

        猜你喜欢
        • 2018-11-21
        • 2021-08-15
        • 2019-03-03
        • 2022-12-24
        • 2021-06-17
        • 2020-09-07
        • 1970-01-01
        • 2020-10-05
        • 2014-06-16
        相关资源
        最近更新 更多