绘制折线图的编程怎么写

时间:2025-03-04 21:07:02 明星趣事

绘制折线图的编程方法取决于你使用的编程语言和可用的库。以下是几种常见编程语言绘制折线图的示例代码:

Python 使用 Matplotlib 库

```python

import matplotlib.pyplot as plt

定义折线图的数据

x = [1, 2, 3, 4, 5]

y = [1, 3, 2, 4, 5]

绘制折线图

plt.plot(x, y)

显示图形

plt.show()

```

Python 使用 matplotlib 库(更多样式设置)

```python

import matplotlib.pyplot as plt

定义折线图的数据

x = [1, 2, 3, 4, 5]

y = [5, 3, 8, 6, 7]

绘制折线图,并设置样式

plt.plot(x, y, '-o', linewidth=2, markersize=8, markeredgecolor='red', markerfacecolor='yellow')

设置图表标题和轴标签

plt.title('折线图示例', fontsize=14)

plt.xlabel('X轴标签')

plt.ylabel('Y轴标签')

显示图表

plt.show()

```

Python 使用 matplotlib 和 numpy 库(处理数据)

```python

import matplotlib.pyplot as plt

import numpy as np

示例数据

x = np.array([11.15, 17.06, 23.42, 35.73, 41.46])

y1 = np.array([46.24, 36.74, 31.97, 26.14, 17.49])

y2 = np.array([-73.29, -74.06, -74.76, -77.45, -79.42])

绘制不规则的上下边界

upper_bound1 = y1 + np.random.uniform(1, 1, size=y1.shape)

lower_bound1 = y1 - np.random.uniform(1, 1, size=y1.shape)

upper_bound2 = y2 + np.random.uniform(1, 1, size=y2.shape)

lower_bound2 = y2 - np.random.uniform(1, 1, size=y2.shape)

设置中文标题

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

绘制折线图

plt.plot(x, y1, label='Line 1')

plt.plot(x, y2, label='Line 2')

设置图表标题和轴标签

plt.title('折线图示例')

plt.xlabel('X轴')

plt.ylabel('Y轴')

显示图例

plt.legend()

显示图表

plt.show()

```

C 语言使用 SDL 库

```c

include

define WIDTH 800

define HEIGHT 600

void drawLine(SDL_Renderer *renderer, int x1, int y1, int x2, int y2) {

SDL_RenderDrawLine(renderer, x1, HEIGHT - y1, x2, HEIGHT - y2);

}

int main() {

SDL_Init(SDL_INIT_VIDEO);

SDL_Window *window = SDL_CreateWindow("Line Chart", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0);

SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

drawLine(renderer, 50, HEIGHT - 50, 750, HEIGHT - 50);

SDL_RenderPresent(renderer);

SDL_Delay(3000);

SDL_DestroyRenderer(renderer);

SDL_DestroyWindow(window);

SDL_Quit();

return 0;

}

```

这些示例代码展示了如何使用不同的编程语言和库来绘制折线图。你可以根据自己的需求和编程环境选择合适的工具和库来实现折线图的绘制。