How to use the variable from the python in rpy2?

邮差的信 提交于 2019-12-14 03:33:26

问题


My simple program extracts the database from Python and store in the variable row.

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)

Now that I am able to get the month and traffic in list a and b like [1000L]

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

Now I want to plot, histogram and piechart out of it. The row contains two coloumns: MOnth and Traffic. I want to convert this into the chart using Rpy2. How do I do it? Here's my table:

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

回答1:


First, make two lists from your database. Something like:

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'])

Then, now you have two python lists, you can make a plot thus:

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

You maybe want lines:

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

You maybe want nice labels:

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


来源:https://stackoverflow.com/questions/11981810/how-to-use-the-variable-from-the-python-in-rpy2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!