Python 中 plt 画柱状图和折线图

本文介绍了Python中使用plt模块进行数据可视化的基础操作,包括如何绘制柱状图和折线图,是数据可视化入门的好帮手。

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

1. 背景

Python在一些数据可视化的过程中需要使用 plt 函数画柱状图和折线图。

 

2. 导入

import matplotlib.pyplot as plt

 

3. 柱状图

array= np.array(array)

plt.hist(array, bins=50,facecolor="red", edgecolor="red" ,linewidth=5,alpha=0.7)

    plt.xlabel("")
    plt.ylabel("")
    plt.title("")

 

4.折线图

plt.figure(figsize=(num_group, 6))
X=[1,2,3,4,5,6,7,8,9]
Y=[1,2,3,4,5,6,7,8,9]#定义折线图的X,Y坐标

plt.plot(X, Y, label=str(model_name)) #折线图

for a, b in zip(X, Y):
    plt.text(a, b, '%.2f
### Python Matplotlib Bar Plot and Line Plot Overlay Example In order to create a chart that overlays both bar and line plots using `matplotlib`, it's important to understand how each type of plot can be added on top of another within the same axes object. This approach allows for complex visualizations where multiple datasets are compared or related trends are highlighted. For instance, when plotting two different types of graphs together such as bars representing volumes alongside lines showing average values over time, specific parameters need adjustment so they do not interfere with one another visually[^3]. Below demonstrates an effective method by creating separate subplot objects but sharing the X-axis between them: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt # Sample Data Creation dates = pd.date_range('20230101', periods=6) df = pd.DataFrame(np.random.rand(6, 2), index=dates, columns=list('AB')) fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('Date') ax1.set_ylabel('Volume', color=color) ax1.bar(df.index, df['A'], color=color, alpha=0.3) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('Average Value', color=color) ax2.plot(df.index, df['B'], color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() plt.show() ``` To ensure no overlap occurs while saving these combined plots into files during automation processes like batch processing scripts, always close figures after saving images through adding `plt.close()` immediately following calls to save functions[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值