Matplotlib添加颜色条

Matplotlib添加颜色条

参考:matplotlib add colorbar

Matplotlib是一个Python中非常流行的绘图库,用于创建各种类型的统计图表和数据可视化。在Matplotlib中,我们可以通过添加颜色条(colorbar)来增强图表的表现力,特别是在显示热图或散点图时。颜色条可以帮助我们更直观地理解数据的分布和趋势。在本文中,我们将介绍如何在Matplotlib中添加颜色条,并提供一些示例代码。

示例代码

示例1:简单添加颜色条

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
plt.colorbar()
plt.show()

Output:

Matplotlib添加颜色条

示例2:自定义颜色条位置和大小

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
cbar = plt.colorbar()
cbar.set_label('Magnitude', rotation=270)
cbar.set_ticks([-1, 0, 1])
cbar.ax.set_yticklabels(['Low', 'Medium', 'High'])
plt.show()

Output:

Matplotlib添加颜色条

示例3:添加颜色条标签

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
plt.colorbar(label='Magnitude')
plt.show()

Output:

Matplotlib添加颜色条

示例4:水平颜色条

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
plt.colorbar(orientation='horizontal')
plt.show()

Output:

Matplotlib添加颜色条

示例5:修改颜色条颜色映射

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='coolwarm')
plt.colorbar()
plt.show()

Output:

Matplotlib添加颜色条

示例6:颜色条范围限制

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
plt.clim(-0.5, 0.5)
plt.colorbar()
plt.show()

Output:

Matplotlib添加颜色条

示例7:隐藏颜色条轴

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
cbar = plt.colorbar()
cbar.outline.set_visible(False)
plt.show()

Output:

Matplotlib添加颜色条

示例8:颜色条格式化值

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.scatter(x, y, c=y, cmap='viridis')
cbar = plt.colorbar(format='%.2f')
plt.show()

Output:

Matplotlib添加颜色条

示例9:使用离散颜色条

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.random.randint(1, 4, 100)

plt.scatter(x, y, c=y, cmap='viridis')
plt.colorbar(ticks=[1, 2, 3])
plt.show()

Output:

Matplotlib添加颜色条

示例10:颜色条分段显示

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

c = np.linspace(0, 1, 100)
plt.scatter(x, y, c=c, cmap='viridis')
plt.colorbar(boundaries=[0, 0.5, 1])
plt.show()

Output:

Matplotlib添加颜色条

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程