0

My Python Pandas Dataframe Looks like this:

enter image description here

I want to plot dates on X-axis and values on Y-axis I am able to get it one at a time. Either X axis or Y axis. I want them together in one graph.

I have tried something like this:

import pandas as pd
from pandas import Series, DataFrame, Panel
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
import matplotlib.pyplot as plt

dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cur = conn.cursor()

df_mysql = pd.read_sql('SELECT PO_Date,PO_Total FROM purchase_order',con=conn)

print df_mysql
po_dates =  df_mysql.ix[:,0]
po_total = df_mysql.ix[:,1]

X = Series( po_total,index=po_dates)
X.plot()
plt.show()

conn.close()

How to plot these 2 columns together?

DavidG
  • 24,279
  • 14
  • 89
  • 82
Rakmo
  • 1,926
  • 3
  • 19
  • 37

3 Answers3

0
  X = Series( po_total.values,index=po_dates)
  X.plot()
Linda
  • 627
  • 4
  • 14
0

it can be even easier and native:

df_mysql.columns = ['po_date','po_total']
df_mysql.plot('po_date','po_total')

the first line (column name assigning) can be done as an argument during the loading itself -pd.read_sql(<args>, columns = ['po_date','po_total'] )

Dimgold
  • 2,748
  • 5
  • 26
  • 49
  • you can just use the plot function twice in two rows. ``matplotlib`` is holding the existing figure by default and letting you present few trendlines together. ``df_mysql.columns = ['po_date','po_total1',po_total2']`` ``df_mysql.plot('po_date','po_total1')`` ``df_mysql.plot('po_date','po_total2')`` – Dimgold Jun 13 '17 at 07:02
0

You may need to convert the date data to datetime format:

Here is an example:

import pandas as pd
# To obtain stock data online, import pandas.io.data namespace, alias as web
from pandas_datareader import data, wb

# datetime for the dates
import datetime
import matplotlib.pyplot as plt

# start end end dates
start = datetime.datetime(2017, 1, 1)
end = datetime.datetime(2017, 6, 9)

# read from Google finance and display the first five rows
ibm = data.DataReader("IBM", 'google', start, end)
ibm.head()

# Create a figure and add an axes in which to plot the data
fig1 = plt.figure(figsize = (5, 3))
ax1 = fig1.add_subplot(1,1,1)

# Define the variables you wish to plot
# The web data reader indexes the dataframe by date; get_level_values
# retrieves those dates from the index
x = ibm.index.get_level_values(0)
y = ibm.Close

ax1.plot(x, y, color = '0.5')

plt.show()
A. Slowey
  • 117
  • 1
  • 2
  • 12
  • My data is already in datetime format. "datetime.date" to be specific. Thanks anyway. Linda's solution was the one I was looking for, – Rakmo Jun 12 '17 at 12:21
  • Glad your problem is solved. Do check out the object-oriented mode of using Matplotlib, though. – A. Slowey Jun 12 '17 at 19:05