Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

r - How to use the variable from the python in rpy2?

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 |
+-----------+---------+
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...