Show Sidebar Hide Sidebar

Plotting from csv data in Python

How to create charts from csv files with Plotly and Python

Plotting from csv Data

CSV or comma-delimited-values is a very popular format for storing structured data. In this tutorial, we will see how to plot beautiful graphs using csv data, and Pandas.

In [1]:
import pandas as pd
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go

A Simple Example

We will import data from a local file sample-data.csv. The file is available here

In [4]:
# Import data from csv
df = pd.read_csv('sample-data.csv')
df.head()
Out[4]:
x cosx logx sinx
0 3.141593 -1.000000 1.144730 1.224647e-16
1 3.147882 -0.999980 1.146730 -6.289433e-03
2 3.154172 -0.999921 1.148726 -1.257862e-02
3 3.160461 -0.999822 1.150718 -1.886730e-02
4 3.166751 -0.999684 1.152706 -2.515525e-02
In [6]:
trace1 = go.Scatter(
                    x=df['x'], y=df['logx'], # Data
                    mode='lines', name='logx' # Additional options
                   )
trace2 = go.Scatter(x=df['x'], y=df['sinx'], mode='lines', name='sinx' )
trace3 = go.Scatter(x=df['x'], y=df['cosx'], mode='lines', name='cosx')

layout = go.Layout(title='Simple Plot from csv data',
                   plot_bgcolor='rgb(230, 230,230)')

fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)

# Plot data in the notebook
py.iplot(fig, filename='simple-plot-from-csv')
Out[6]:

Plotting data from external source

In the next example, we will learn how to import csv data from an external source (a url), and plot it using Plotly and pandas. We are going to use this data for the example.

In [7]:
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv')
In [8]:
df.head()
Out[8]:
AAPL_x AAPL_y
0 2014-01-02 77.445395
1 2014-01-03 77.045575
2 2014-01-06 74.896972
3 2014-01-07 75.856461
4 2014-01-08 75.091947
In [11]:
trace = go.Scatter(
                  x = df['AAPL_x'], y = df['AAPL_y'],
                  name='Share Prices (in USD)'
                  )
layout = go.Layout(
                  title='Apple Share Prices over time (2014)',
                  plot_bgcolor='rgb(230, 230,230)',
                  showlegend=True
                  )
fig = go.Figure(data=[trace], layout=layout)

py.iplot(fig, filename='apple-stock-prices')
Out[11]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to our Premium or Enterprise plans.