如何在rpy2中使用python中的变量?

时间:2012-08-16 06:31:26

标签: python r rpy2

我的简单程序从Python中提取数据库并存储在变量行中。

cursor = con.cursor()       
    cursor.execute("SELECT * FROM traffic")

    #Retrieves data from SQL
    rows = cursor.fetchall()  

    for row in rows:
       row = list(row)
       a = row[1:]
       b = row[:-1]
       print(a)
       print(b)

现在我能够获得列表a和b中的月份和流量,如[1000L]

['January']
[100L]
['February']
[10430L]
['March']
[1500L]
['April']
[100L]
['May']
[1200L]
['June']
[800L]
['July']
[8000L]
['August']
[100000L]
['September']

现在我想用它绘制直方图,直方图和饼图。 该行包含两个颜色:MOnthTraffic。我想使用Rpy2将其转换为图表。我该怎么做?这是我的表:

month     | traffic |
+-----------+---------+
| January   |    1000 |
| February  |     100 |
| March     |   10430 |
| April     |    1500 |
| May       |     100 |
| June      |    1200 |
| July      |     800 |
| August    |    8000 |
| September |  100000 |
+-----------+---------+

1 个答案:

答案 0 :(得分:1)

首先,从数据库中创建两个列表。类似的东西:

cursor = con.cursor()       
cursor.execute("SELECT * FROM traffic")

#Retrieves data from SQL
rows = cursor.fetchall()  

Month = list()
Traffic = list()

for row in rows:
    Month.append(row['Month'])          # guesswork - what does a row look like?
    Traffic.append(row['Traffic'])

然后,现在你有两个python列表,你可以制作一个情节:

>>> r.plot(Month,Traffic)
rpy2.rinterface.NULL

你可能想要一行:

>>> r.plot(Month,Traffic,type="l")
rpy2.rinterface.NULL

您可能需要不错的标签:

>>> r.plot(Month,Traffic,type="l",xlab="Month",ylab="Traffic")