Re: [問題] 關於用matplotlib如何把資料丟進圖裡
※ 引述《Nccu3631 (政大鄭人維)》之銘言:
: 對於matplotlib
: 在網路上找了很久
: 覺得這個工具很不熟
: 關於現在的問題是
: 我有一筆資料 是關於 水果在那些市集有販賣
: 而畫了一個基本表格
: import numpy as np
: import matplotlib.pyplot as plt
: plt.title("Total fruit :%d " %kk)
: xticks = np.arange(20,140,20)
: yticks = np.arange(1, 11, 1)
matplotlib 畫圖的方式很原始,畫長條圖,你就要給它每個 bar 的位置與長度。
以你這邊的給法,似乎是要畫橫的長條圖,但又跟後面的語句有衝突。
簡單一點就先假設是最常見的長條圖:
y
| n
| n n
| n n
+--------- x
: 這是我所畫的
: 想要丟的資料相當於一個list
: fruitlist=['apple':123 ,'banana':156,'orange':589,'blueberry':145,'cherry':23]
這個不是 list 喔,你的語法比較像 dict。
但直接用 dict 畫圖會無法保証每個水果出現的順序(蘋果不一定在香蕉前面)
這邊推薦用 collections.OrderedDict。
# 我是註解
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
my_fruits = OrderedDict([
('apple', 123), ('banana', 156), ('orange', 589),
('blueberry', 145), ('cherry', 23)
])
# 給定每個 bar 出現的 X 座標
# 通常間隔都一樣,就讓它出現在 x = 1, 2, ..., N
xticks = np.arange(len(my_fruits)) + 1
# 真正畫長條圖的函式 plt.bar(...)
# bar 座標 每個 bar 高度 置中表示第一個 bar 中央的座標是 (1, ...)
plt.bar(xticks, my_fruits.values(), align='center')
plt.xticks(xticks, list(my_fruits.keys())) # 預設 X 座標數字,改顯示水果名
plt.title("Total fruit: %d" % len(my_fruits)) # 給標題
plt.show() # 秀出圖。不一定需要,例如在 inline 模式就不需要
matplotlib 設計是仿 MATLAB 繪圖方式,個人覺得非常底層,
雖然這讓它畫複雜的圖時非常方便,但簡單如長條圖畫起來都很囉嗦。
像 R 的 ggplot2 或它 Py ported 版本 ggplot 就好上手多了(被打)
橫的長條圖可以參考官網範例:
http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html
另外如果你有在用 pandas 處理表格類的數據的話
import pandas as pd
df = pd.DataFrame(list(my_fruits.items()), columns=['Fruit', 'Count'])
df.plot(kind='bar', x=0, title='My Fruits')
會是一樣的效果~
--
PyCon APAC 2015 歡迎大家關注與加入! http://tw.pycon.org/
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 117.136.0.145
※ 文章網址: http://www.ptt.cc/bbs/Python/M.1414503698.A.41A.html
※ 編輯: ccwang002 (117.136.0.145), 10/28/2014 21:56:06
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章