📜  如何使用 CSV 文件在Python绘制条形图?

📅  最后修改于: 2022-05-13 01:55:48.794000             🧑  作者: Mango

如何使用 CSV 文件在Python绘制条形图?

CSV表示“逗号分隔值”,这意味着这些值通过将逗号和字符区分。 CSV 文件提供了一种类似于表格的格式,几乎所有电子表格阅读器(如 Microsoft Excel 和 Google 电子表格)都可以读取该格式。

条形图使用标签和值,其中标签是特定条形的名称,值表示条形的高度。条形图常用于数据分析中,我们希望在其中比较数据并提取最常见或最高的组。

在这篇文章中,我们将学习如何使用 CSV 文件绘制条形图。有很多模块可用于读取 .csv 文件,如 csv、pandas 等。但在本文中,我们将手动读取 .csv 文件以了解其工作原理。

使用的功能

  • Pandas read_csv()函数用于读取 csv 文件。

句法:

  • Matplotlib 的 bar()函数用于创建条形图

句法:

方法一:使用熊猫

方法

  • 导入模块
  • 使用 read_csv()函数读取文件
  • 绘制条形图
  • 显示图表

例子:

使用中的数据集:点击这里

Python3
# Import the necessary modules
import matplotlib.pyplot as plt
import pandas as pd
  
  
# Initialize the lists for X and Y
data = pd.read_csv('C:\\Users\\Vanshi\\Desktop\\data.csv')
  
df = pd.DataFrame(data)
  
X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])
  
# Plot the data using bar() method
plt.bar(X, Y, color='g')
plt.title("Students over 11 Years")
plt.xlabel("Years")
plt.ylabel("Number of Students")
  
# Show the plot
plt.show()


Python3
# Import the modules
import matplotlib.pyplot as plt
  
# Initialize a dictionary for months
data = dict()
  
# Read the data
with open('electronics.csv', 'r') as f:
    for line in f.readlines():
        
        # Store each line in the dictionary
        month, item, quantity = line.split(',')
          
        if month not in data:
            data[month] = []
        data[month].append((item, int(quantity)))
  
# Position of each subplot where 221 means 2 row,
# 2 columns, 1st index
positions = [221, 222, 223, 224]
  
# Colors to distinguish the plot
colors = ['r', 'g', 'b', 'y']
  
# Plot the subgraphs
for i, l in enumerate(data.keys()):
    plt.subplot(positions[i])
    data_i = dict(data[l])
    plt.bar(data_i.keys(), data_i.values(), color=colors[i])
    plt.xlabel(l)
  
# Show the plots
plt.show()


输出:



方法二:使用 Matplotlib

方法

  • 导入模块
  • 打开文件
  • 读取数据
  • 绘制条形图
  • 显示图表

程序:

使用中的数据集:单击此处下载此文件。

蟒蛇3

# Import the modules
import matplotlib.pyplot as plt
  
# Initialize a dictionary for months
data = dict()
  
# Read the data
with open('electronics.csv', 'r') as f:
    for line in f.readlines():
        
        # Store each line in the dictionary
        month, item, quantity = line.split(',')
          
        if month not in data:
            data[month] = []
        data[month].append((item, int(quantity)))
  
# Position of each subplot where 221 means 2 row,
# 2 columns, 1st index
positions = [221, 222, 223, 224]
  
# Colors to distinguish the plot
colors = ['r', 'g', 'b', 'y']
  
# Plot the subgraphs
for i, l in enumerate(data.keys()):
    plt.subplot(positions[i])
    data_i = dict(data[l])
    plt.bar(data_i.keys(), data_i.values(), color=colors[i])
    plt.xlabel(l)
  
# Show the plots
plt.show()

输出: