matplotlib简单使用给出完整代码示例
时间: 2023-09-05 21:13:31 浏览: 47
以下是一个简单的matplotlib代码示例,用于绘制一个简单的折线图:
```python
import matplotlib.pyplot as plt
# 构建数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 绘制折线图
plt.plot(x, y)
# 设置标题和轴标签
plt.title("My Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# 显示图像
plt.show()
```
这个示例中,我们首先导入了matplotlib库,并创建了两个列表x和y来存储我们的数据。然后,我们使用plt.plot()函数绘制了一个折线图,并使用plt.title()、plt.xlabel()、plt.ylabel()函数设置了标题和轴标签。最后,我们使用plt.show()函数显示了图像。
相关问题
matplotlib画散点图参数设置代码示例
下面是一个简单的 matplotlib 画散点图的代码示例,其中包含了一些常用的参数设置:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
# 画散点图
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, edgecolors='none')
# 设置坐标轴范围
plt.xlim(0, 1)
plt.ylim(0, 1)
# 设置坐标轴标签
plt.xlabel('X Label')
plt.ylabel('Y Label')
# 添加标题
plt.title('Scatter Plot Example')
# 显示图形
plt.show()
```
在上面的代码中,我们通过 `plt.scatter()` 函数画出了一个散点图,并设置了以下参数:
- `x` 和 `y`:分别为 x 轴和 y 轴的数据;
- `c`:设置散点的颜色;
- `s`:设置散点的大小;
- `alpha`:设置散点的透明度;
- `edgecolors`:设置散点的边缘颜色。
另外,我们还设置了坐标轴范围、坐标轴标签和标题等。通过这些参数的设置,我们可以画出不同类型的散点图。
pyqt5 QLineEdit使用matplotlib绘制的图形,代码示例
下面是一个简单的示例代码,使用 PyQT5 的 QLineEdit 控件和 Matplotlib 库绘制图形:
```python
import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QLineEdit
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# 创建一个 QWidget
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
# 创建一个 QVBoxLayout,并将 QWidget 设置为布局
layout = QVBoxLayout(centralWidget)
# 创建一个 QLineEdit
self.lineEdit = QLineEdit(self)
layout.addWidget(self.lineEdit)
# 创建一个 FigureCanvas
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
layout.addWidget(self.canvas)
# 在 Figure 中绘制图形
self.ax = self.figure.add_subplot(111)
x = np.linspace(-10, 10, 100)
self.ax.plot(x, np.sin(x))
# 将 QLineEdit 的文本更新时绘制新的图形
self.lineEdit.textChanged.connect(self.updatePlot)
def updatePlot(self):
# 获取 QLineEdit 的文本
text = self.lineEdit.text()
# 在 Figure 中绘制新的图形
x = np.linspace(-10, 10, 100)
y = eval(text)
self.ax.clear()
self.ax.plot(x, y)
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
```
这个示例程序创建了一个包含 QLineEdit 控件和 Matplotlib 图形的 PyQT5 窗口。当用户在 QLineEdit 中输入表达式时,程序会绘制新的图形。注意,在这个示例中,我们使用了 eval 函数将用户的输入作为 Python 代码执行。为了安全起见,你应该在真实的应用程序中采用更加谨慎的方法来执行用户输入的代码。