从数据库提取的10k记录散点图
我正在尝试在Python中制作一个散点图。我原以为这会很简单,但在理解散点图(x和y值)时遇到了困难。
==我的任务 ==
- 我有一个数据库,目前有超过1万条记录(都是浮点数),并且每天都会增加。
- 这些记录的范围是从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()
散点图的理解 (链接)
好的!这个图看起来没有任何意义。
==问题 ==
- 如何制作散点图,以查看数据最多的区域?
- 我该如何设置y变量,使其与x变量(获取的记录总数)保持相同的维度?
我对绘图和统计学还很陌生,所以请帮帮我。
2 个回答
2
在散点图中,你需要有相同数量的x值和y值。通常在散点图里,一个变量是另一个变量的函数,或者至少两个变量都有数字值。比如,你可以有x值[1, 2, 3]和y值[4, 5, 6],这样在一个二维图上,(x, y)的点(1, 4)、(2, 5)和(3, 6)就会被绘制出来。
在你的情况中,似乎只有x值,没有y值,而你又把y值固定了。根据我的理解,我们不能这样生成散点图。每个x值都需要对应一个y值。你可以尝试用序号作为y值,但在图上可能看起来没什么意义。
3
也许你在寻找matplotlib的直方图:
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()
你也可以使用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()
关于使用pylab:pyplot的文档中提到
matplotlib.pylab
把pyplot和numpy合并到一个命名空间中。这对于互动工作很方便,但在编程时建议保持命名空间分开。