1. 程式人生 > 實用技巧 >Python for Data Science - Creating standard data graphics

Python for Data Science - Creating standard data graphics

Chapter 4 - Practical Data Visualization

Segment 1 - Creating standard data graphics

import numpy as np
from numpy.random import randn
import pandas as pd
from pandas import Series, DataFrame

import matplotlib.pyplot as plt
from matplotlib import rcParams

Creating a line chart from a list object

Plotting a line chart in matplotlib

x = range(1,10)
y = [1,2,3,4,0,4,3,2,1]

plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x7f361b7a7780>]

Plotting a line chart from a Pandas object

address = '~/Data/mtcars.csv'

cars = pd.read_csv(address)
cars.columns = ['car_names','mpg','cyl','disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb']

mpg = cars['mpg']
mpg.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f361afafd30>

df = cars[['cyl','wt','mpg']]
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f361af44e80>

Creating bar charts

Creating a bar chart from a list

plt.bar(x,y)
<BarContainer object of 9 artists>

Creating bar charts from Pandas objects

mpg.plot(kind="bar")
<matplotlib.axes._subplots.AxesSubplot at 0x7f361ae4a710>

mpg.plot(kind="barh")
<matplotlib.axes._subplots.AxesSubplot at 0x7f361af44400>

Creating a pie chart

x = [1,2,3,4,0.5]
plt.pie(x)
plt.show()

Saving a plot

plt.pie(x)
plt.savefig('plt_chart.png')
plt.show()

%pwd
'/home/ericwei/Ex_Files_Python_Data_Science_EssT_Pt_1/Exercise Files/04_01_begin'