2012-01-04 76 views
3

我想在Python中製作散點圖。我認爲這將是相當簡單的,但在繪圖時陷於散點圖(x和y值)的理解中。從數據庫中提取的10k記錄的散點圖

== 我的任務 ==

  • 我有數據庫和更多然後10K記錄(ALL浮點)到現在爲止,並每天都在增加。
  • 記錄範圍是從200-2000(浮點十進制)。
  • 所以,我想看看我的數據集中人口最稠密的地區。

== 我做了什麼? ==

import numpy as np 
import pylab as pl 
import MySQLdb 
import sys 
import math 

conn = MySQLdb.connect(
    host="localhost", 
    user="root", 
    passwd="root", 
    db="myproject") 

with conn: 
    cur = conn.cursor() 

    #will fetch all recoreds called monoiso field 
    cur.execute("SELECT monoiso FROM pmass_selectedion") 
    rows = cur.fetchall() 

    for row in rows: 

     #xvalue for monoiso variable and yvalue for range 
     xvalue = row 
     yvalue = [600] 

     # tried this way too but got x and y dimension error 
     #yvalue = [400,800,1200,1600] 

     pl.plot(xvalue,yvalue,'ro') 
pl.show() 

散點圖瞭解link

enter image description here

好!這個情節沒有任何意義。

== 問題 ==

  • 如何使散點圖看到人口最稠密的地區?
  • 我該如何分配y變量與x變量(獲取記錄的總數)做同等維數?

新建繪圖和統計,請幫我出

回答

3

也許你正在尋找a matplotlib histogram

import numpy as np 
import MySQLdb 
import matplotlib.pyplot as plt # This is meant for scripts 
# import pylab as pl # This is meant for interactive sessions; 
import operator 

conn = MySQLdb.connect(
    host="localhost", 
    user="root", 
    passwd="root", 
    db="myproject") 

with conn: 
    cur = conn.cursor() 

    #will fetch all recoreds called monoiso field 
    cur.execute("SELECT monoiso FROM pmass_selectedion") 
    rows = cur.fetchall() 

monoisos = [row[0] for row in rows] 

# Make a histogram of `monoisos` with 50 bins. 
n, bins, histpatches = plt.hist(monoisos, 50, facecolor = 'green') 
plt.show() 

enter image description here


你也可以做一個直方圖/點 - 使用numpy.histogram

momoisos = [row[0] for row in rows] 
hist, bin_edges = np.histogram(monoisos, bins = 50) 
mid = (bin_edges[1:] + bin_edges[:-1])/2 
plt.plot(mid, hist, 'o') 
plt.show() 

enter image description here


關於使用pylab的:對pyplot文檔字符串表示

matplotlib.pylab結合numpy的pyplot成一個單一命名空間。 這對於交互式工作很方便,但對於編程,建議將名稱空間分開保存,即 。

+0

@ unutbu-這似乎是完美的直方圖,但想知道是否可能通過散點圖或任何其他點圖? – thchand 2012-01-04 18:49:33

+0

是的,我添加了一個使用'numpy.histogram'構建直方圖值的示例,然後使用'plt.plot'來繪製點圖。 – unutbu 2012-01-04 18:57:21

+0

+1,但我真的會用一個簡單的'[v [行]中的v [0]]替換'import operator ... map(operator.itemgetter(0),rows)''。 – EOL 2012-01-04 22:48:01

2

對於散點圖,需要相同數量的x和y值。通常在散點圖中,其中一個變量是另一個變量的函數,或者至少兩個變量都具有數值。例如,你可以得到x值[1,2,3]和y值[4,5,6],然後在2維圖上,(1,4),(2)的(x,y) ,5)和(3,6)將被繪製。

就你而言,在我看來,沒有y值,但只有x值,你保持y固定。從我看來,我們無法生成這樣的散點圖。我們需要一個對應於每個x值的y值。你可以嘗試序列號爲y,但在情節中可能沒有太大意義。

+0

關於我的上面的帖子:直方圖可能真的符合這裏的法案。 – Ambidextrous 2012-01-04 18:44:43

+0

@ Ambidextrous-很好的清晰感謝! – thchand 2012-01-04 18:51:20