在 Matplotlib 中显示颜色条
在本篇文章中,我们将讨论如何在 Python 中的 matplotlib 图形中显示颜色条。
要创建颜色条,我们必须使用 matplotlib.pyplot.colorbar()
函数。
下面的代码显示了一个简单的例子。
import random
import matplotlib.pyplot as plt
s_x = random.sample(range(0,100),20)
s_y = random.sample(range(0,100),20)
s = plt.scatter(s_x,s_y,c = s_x, cmap='viridis')
c = plt.colorbar()
在上面的示例中,我们创建了一个放置在绘图之外的简单颜色条。我们使用 cmap
参数指定了颜色图。
我们还可以指定我们希望显示颜色条的轴。如果我们愿意,我们可以将它添加到绘图的轴上。
例如,
import random
import matplotlib.pyplot as plt
s_x = random.sample(range(0,100),20)
s_y = random.sample(range(0,100),20)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.scatter(s_x,s_y,c = s_x, cmap = "viridis")
fig.colorbar(im, cax = cax, orientation = 'horizontal')
在上面的示例中,我们使用 subplots()
函数来获取图形和轴对象,并使用它来创建颜色条的轴。我们使用 colorbar()
函数中的 cax
参数指定了这一点。
另外,请注意 orientation
参数的使用,它改变了最终颜色条的方向。除此之外,我们可以使用不同的参数来控制颜色条的形状和大小。例如,shrink
可以将颜色条的大小缩小一小部分,aspect
,这是条边的比例,还有更多。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串