如何使用Pandas绘制数据框架

如何使用Pandas绘制数据框架

Pandas是数据科学中最流行的Python软件包之一。Pandas提供了一个强大而灵活的数据结构(**Dataframe & Series **)来操作和分析数据。可视化是解释数据的最佳方式。

Python有许多流行的绘图库,使可视化变得容易。其中一些是matplotlib, seaborn, 和 plotly。它与matplotlib有很好的集成。我们可以使用plot()方法绘制一个数据框架。但是我们需要一个数据框架来绘制。我们可以通过向pandas库的DataFrame()方法传递一个字典来创建一个数据框架。

让我们创建一个简单的数据框架。

# importing required library
# In case pandas is not installed on your machine
# use the command 'pip install pandas'. 
import pandas as pd
import matplotlib.pyplot as plt
  
# A dictionary which represents data
data_dict = { 'name':['p1','p2','p3','p4','p5','p6'],
              'age':[20,20,21,20,21,20],
              'math_marks':[100,90,91,98,92,95],
              'physics_marks':[90,100,91,92,98,95],
              'chem_marks' :[93,89,99,92,94,92]
              }
  
# creating a data frame object
df = pd.DataFrame(data_dict)
  
# show the dataframe
# bydefault head() show 
# first five rows from top
df.head()
Python

输出:

如何使用Pandas绘制数据框架?

Plots

有许多图可以用来解释数据。每个图都有其用途。其中一些图是条形图、散点图和直方图等。

Scatter Plot:

要获得一个数据框架的散点图,我们所要做的就是通过指定一些参数调用plot()方法。

kind='scatter',x= 'some_column',y='some_colum',color='somecolor'
Python
# scatter plot
df.plot(kind = 'scatter',
        x = 'math_marks',
        y = 'physics_marks',
        color = 'red')
  
# set the title
plt.title('ScatterPlot')
  
# show the plot
plt.show()
Python

输出:

如何使用Pandas绘制数据框架?

有许多方法可以定制情节,这是基本的方法。

Bar Plot:

同样地,我们必须为plot()方法指定一些参数,以获得条形图。

kind='bar',x= 'some_column',y='some_colum',color='somecolor'
Python
# bar plot
df.plot(kind = 'bar',
        x = 'name',
        y = 'physics_marks',
        color = 'green')
  
# set the title
plt.title('BarPlot')
  
# show the plot
plt.show()
Python

输出:

如何使用Pandas绘制数据框架?

Line Plot:

单一列的线图并不总是有用的,为了获得更多的洞察力,我们必须在同一个图上绘制多个列。要做到这一点,我们必须重新使用坐标axis。

kind=’line’,x= ‘some_column’,y=’some_colum’,color=’somecolor’,ax=’someaxes’

#Get current axis
ax = plt.gca() 
  
# line plot for math marks
df.plot(kind = 'line',
        x = 'name',
        y = 'math_marks',
        color = 'green',ax = ax)
  
# line plot for physics marks
df.plot(kind = 'line',x = 'name',
        y = 'physics_marks',
        color = 'blue',ax = ax)
  
# line plot for chemistry marks
df.plot(kind = 'line',x = 'name',
        y = 'chem_marks',
        color = 'black',ax = ax)
  
# set the title
plt.title('LinePlots')
  
# show the plot
plt.show()
Python

输出:

如何使用Pandas绘制数据框架?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册