如何使用Python在 Matplotlib 中更改图形的颜色?
先决条件: Matplotlib
Python提供了大量用于绘制图形的库,而 Matplotlib 就是其中之一。 Matplotlib 是一个简单易用的库,用于创建高质量的图形。 matplotlib 的 pyplot 库包含使 matplotlib 像 matlab 一样工作的命令和方法。 pyplot 模块用于设置图形标签、图表类型和图表颜色。以下方法用于图形的创建和图形的相应颜色变化。
Syntax: matplotlib.pyplot.bar(x, height, width, bottom, align, **kwargs)
Parameter:
- x : sequence of scalers along the x axis
- height : sequence of scaler determining the height of bar ie y-axis
- width : width of each bar
- bottom : Used to specify the starting value along the Y axis.(Optional)
- align : alignment of the bar
- **kwargs : other parameters one of which is color which obviously specifies the color of the graph.
Return Value: Returns the graph plotted from the specified columns of the dataset.
在本文中,我们使用从 kaggel.com 下载的数据集作为下面给出的示例。使用的数据集代表国家与已确认的 covid-19 病例数量。数据集可以从给定的链接下载:
数据集链接: Corona 病毒报告
示例 1:
Python3
# import packages
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# import dataset
df = pd.read_csv('country_wise_latest.csv')
# select required columns
country = df['Country/Region'].head(10)
confirmed = df['Confirmed'].head(10)
# plotting graph
plt.xlabel('Country')
plt.ylabel('Confirmed Cases')
plt.bar(country, confirmed, color='green', width=0.4)
# display plot
plt.show()
Python3
# import packages
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# import dataset
df = pd.read_csv('country_wise_latest.csv')
# select required data
country = df['Country/Region'].head(20)
confirmed = df['Active'].head(20)
# plot graph
plt.xlabel('Country')
plt.ylabel('Active Cases')
plt.bar(country, confirmed, color='maroon', width=0.4)
# display plot
plt.show()
输出
示例 2:
蟒蛇3
# import packages
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# import dataset
df = pd.read_csv('country_wise_latest.csv')
# select required data
country = df['Country/Region'].head(20)
confirmed = df['Active'].head(20)
# plot graph
plt.xlabel('Country')
plt.ylabel('Active Cases')
plt.bar(country, confirmed, color='maroon', width=0.4)
# display plot
plt.show()
输出