matplotlib可视化

本文详细介绍了Python的Matplotlib库如何用于数据可视化,包括安装、简单线图、散点图、条形图、多组数据的图形绘制以及直方图的创建。通过实例展示了如何使用pyplot模块的不同功能,如设置线条颜色、线型、标签等,以及如何在一个图形中绘制多个图表。此外,还解释了如何通过子图功能在同一图形中展示多个图,以及如何使用条形图和直方图来表示不同类别的数据分布。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Matplotlib is a very powerful data visualization library if you want to plot data with Python. The most used module is ‘pyplot’ which provides a collection of functions that lets you easily plot out data.

如果要使用Python绘制数据, Matplotlib是一个非常强大的数据可视化库。 最常用的模块是“ pyplot ”,它提供了一组功能,可让您轻松地绘制数据。

安装 (Installation)

Using conda:

使用conda:

conda install matplotlib

Using pip:

使用点子:

pip install matplotlib

As a prerequisite, you must have the basic knowledge of what Python dictionaries and lists are, as well as features and functions of Python’s Numpy library.

前提条件是,您必须具有有关什么是Python字典列表以及Python的Numpy库的特性和功能的基本知识。

简单线图 (Simple line graph)

Import the necessary modules.

导入必要的模块。

import numpy as np
import matplotlib.pyplot as plt

Simple line graphs are the most commonly plotted graphs and are generally used to plot data that is tracked over a period of time like stock prices.

简单的折线图是最常用的绘图图,通常用于绘制在一段时间内跟踪的数据(例如股票价格)。

Lets create the same using pyplot by passing in a simple python list.

让我们通过传入一个简单的python列表使用pyplot创建相同的内容。

plt.plot([2,4,5,10])
Image for post
Image by author
图片作者

Here you can see the plot of our 4 values.

在这里,您可以看到我们4个值的曲线图。

If you provide a single list of values to the plot function, matplotlib will assume that they are y values and automatically generates the x values for you. The default x vector has the same length as the list you pass into the function but it starts with 0. Above we can see the x plot values are 0, 1, 2, and 3.

如果您为plot函数提供一个值列表,则matplotlib将假定它们为y值并自动为您生成x值。 默认的x向量的长度与您传递给函数的列表的长度相同,但它以0开头。在上面我们可以看到x的绘图值为0、1、2和3。

To plot x versus y, you can pass 2 lists into the function. First of which is the x vector and then the y vector.

要绘制x与y的关系图,可以将2个列表传递给函数。 首先是x向量,然后是y向量。

plt.plot([1,3,7,10], [2,4,5,10])
Image for post
Image by author
图片作者

Here we can see a different set of x values for our y values. The first x value corresponds to the first y value and so on.

在这里,我们可以看到一组不同的x值作为y值。 第一个x值对应于第一个y值,依此类推。

散点图 (Scatter plots)

Scatter plots use dots to represent values for two distinct numeric variables.

散点图使用点表示两个不同的数字变量的值。

You can pass in a third argument to the plot function to indicate the format of the color and the line type of the plot.

您可以将第三个参数传递给绘图函数,以指示颜色的格式和绘图的线型。

To obtain a scatter plot with in the color red, we add ‘ro’ as the third argument.

为了获得红色的散点图,我们将“ ro”添加为第三个参数。

plt.plot([1,3,7,10], [2,4,5,10], 'ro')
Image for post
Image by author
图片作者

So here we can see that our plot is converted from a blue line to red circles.

因此,在这里我们可以看到我们的绘图从蓝线转换为红色圆圈。

Generally, we use NumPy arrays instead of Python lists while working with plots in matplotlib as show below.

通常,在matplotlib中使用图时,我们使用NumPy数组而不是Python列表,如下所示。

a = np.array([[12,23,34,45],
[56,67,78,89]])
plt.plot(a[0], a[1], 'go')
Image for post
Image by author
图片作者

We can also add labels to our axes.

我们还可以在轴上添加标签。

plt.xlabel('x-axis')
plt.ylabel('y-axis')plt.plot(a[0], a[1], 'p--')
Image for post
Image by author
图片作者

图形中的多组数据(Multiple sets of data in a graph)

To plot multiple sets of data on a graph, pass multiple sets of arguments in the plot function. Let’s create an array that has a few evenly spaced numbers to understand how we can do this.

要在图形上绘制多组数据,请在plot函数中传递多组参数。 让我们创建一个具有几个均匀间隔的数字的数组,以了解我们如何做到这一点。

t = np.linspace(0, 5, 10) 
plt.plot(t, t**2, color = 'red', linestyle = '--')
Image for post
Image by author
图片作者

‘linspace’ is a NumPy function and ‘linestyle’ is a pyplot parameter.

“ linspace”是NumPy函数,“ linestyle”是pyplot参数。

If I wanted to plot another line on this line, I can easily do that by calling the plot function again.

如果要在这条线上绘制另一条线,可以通过再次调用plot函数轻松地做到这一点。

plt.plot(t, t**2, color = 'red', linestyle = '--')
plt.plot(t, t*3, color='green', linewidth = 2)
Image for post
Image by author
图片作者

Here, ‘linewidth’ is a pyplot parameter. As you can see the second line is printed on top of our previous line.

此处,“ linewidth”是pyplot参数。 如您所见,第二行打印在我们上一行的顶部。

绘制多个图 (Plotting multiple graphs)

We can use the subplot function to add more than one plot in one figure. This option takes three arguments: the number of rows, the number of columns and the index.

我们可以使用子图功能在一个图形中添加多个图。 该选项采用三个参数:行数,列数和索引。

plt.subplot(1,3,1)
plt.plot(t,t,'c--')
Image for post
Image by author
图片作者

Using the same subplot method we can create more plots of different types right next to our existing plot.

使用相同的子图方法,我们可以在现有图旁边创建更多不同类型的图。

plt.subplot(1,3,1)
plt.plot(t,t,'c--')plt.subplot(1,3,2)
plt.plot(t,t**2,'b-')plt.subplot(1,3,3)
plt.plot(t,t**3,'mo')
Image for post
Image by author
图片作者

条形图(Bar graphs)

Furthermore, we can plot data using bar graphs which are one of the most common types of graphs. Bar graphs are used to show data that are split into different categories. For example, if I want to sales of different products I would use a bar graph to do that.

此外,我们可以使用条形图绘制数据,条形图是最常见的图形类型之一。 条形图用于显示分为不同类别的数据。 例如,如果我想销售其他产品,则可以使用条形图来实现。

sales = {'Computers': 92,
'Laptops': 76,
'Mobiles': 97,
'TVs': 82,
'Speakers': 70}
plt.bar(range(len(sales)), list(sales.values()), color = 'pink')
Image for post
Image by author
图片作者

In our example, the x coordinates range from 0 to 4 and y coordinates shows the height of each bar. We can see a bar graph of the values in our dictionary. The height of each bar represents the sales made in that category.

在我们的示例中,x坐标的范围是0到4,y坐标显示了每个条形的高度。 我们可以在字典中看到条形图。 每个条形图的高度代表该类别中的销售额。

If we want to change these numbers to the names of the categories we can do it as shown below.

如果要将这些数字更改为类别的名称,可以如下所示进行操作。

plt.bar(range(len(sales)), list(sales.values()), color = 'pink')
plt.xticks(range(len(sales)), list(sales.keys()))
Image for post
Image by author
图片作者

Here we can see that under each bar, we have the corresponding names of the categories. Similarly, if we want to change the x and y labels we can use the same ‘plt.xlabel’ and ‘plt.ylabel’ functions.

在这里,我们可以看到在每个条形下,都有相应的类别名称。 同样,如果要更改x和y标签,可以使用相同的'plt.xlabel'和'plt.ylabel'函数。

plt.bar(range(len(sales)), list(sales.values()), color=’pink’)
plt.xticks(range(len(sales)), list(sales.keys()))
plt.xlabel(“Categories”)
plt.ylabel(“Sales”)
Image for post
Image by author
图片作者

The last type of graphs that we will look at in this article are histograms. Histograms are a very common type of graph when we’re looking at data like height and weight, stock prices, etc. In our example, let's generate a random continuous data of about 1000 entries.

我们将在本文中讨论的最后一种图形是直方图。 当我们查看身高,体重,股票价格等数据时,直方图是一种非常常见的图形。在我们的示例中,让我们生成约1000个条目的随机连续数据。

x = np.random.randn(1000)
plt.hist(x, color = 'green')
Image for post
Image by author
图片作者

Here we can see our histogram has a distribution of numbers from -4 to 3. And it peaks around 0 which means the bulk of our area lies there.

在这里,我们可以看到直方图的数字分布范围为-4到3。它的峰值在0附近,这意味着我们的大部分区域都位于该位置。

That’s it for this article.

本文就是这样。

Click here to view the code for this tutorial.

单击此处查看本教程的代码。

Thank you for giving it a read!

感谢您阅读!

翻译自: https://towardsdatascience.com/visualizations-with-matplotlib-4809394ea223

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值