Python - 根据值绘制彩色网格

Python - Plotting colored grid based on values(Python - 根据值绘制彩色网格)
本文介绍了Python - 根据值绘制彩色网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这里和网上搜索.我以某种方式找到了我想要的问题/答案,但仍然无法达到我正在寻找的东西.

我有一个数组,例如 100 个值.值在 0 到 100 的范围内.我想将此数组绘制为网格,根据数组中的值填充正方形.

目前我找到的解决方案如下:

有关更多信息,您可以查看此 matplotlib 示例.

I have been searching here and on the net. I found somehow close questions/answers to what I want, but still couldn't reach to what I'm looking for.

I have an array of for example, 100 values. The values are in the range from 0 to 100. I want to plot this array as a grid, filling the squares according to the values in the array.

The solutions I found so far are like the followings:

Drawing grid pattern in matplotlib

and

custom matplotlib plot : chess board like table with colored cells

In the examples I mentioned, the ranges of the colors vary and are not fixed.

However, what I am wondering about, is whether I can set the ranges for specific values and colors. For example, if the values are between 10 and 20, let the color of the grid square be red. else if the values are between 20 and 30, let the color be blue. etc.

How this could be achieved in python?

解决方案

You can create a ListedColormap for your custom colors and color BoundaryNorms to threshold the values.

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

data = np.random.rand(10, 10) * 20

# create discrete colormap
cmap = colors.ListedColormap(['red', 'blue'])
bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots()
ax.imshow(data, cmap=cmap, norm=norm)

# draw gridlines
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
ax.set_xticks(np.arange(-.5, 10, 1));
ax.set_yticks(np.arange(-.5, 10, 1));

plt.show()

Resulting in;

For more, you can check this matplotlib example.

这篇关于Python - 根据值绘制彩色网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)