- Plotting Data Online via Plotly and Python
- Getting Started
- Creating a Graph
- Converting to a Bar Chart
- Saving the Graph to Disk
- Wrapping Up
- Online Matplotlib Compiler (Matplotlib 3.7.0)
- How to give program Input?
- Keyboard Shortcuts
- Save Matplotlib Project
- Share Matplotlib Project
- Python Online Compiler
- Taking inputs (stdin)
- About Python
- Tutorial & Syntax help
- Loops
- 1. If-Else:
- Note:
- 2. For:
- Example:
- 3. While:
- Collections
- 1. List:
- Example:
- 2. Tuple:
- Example:
- 3. Set:
- Example:
- 4. Dictionary:
- Example:
- Supported Libraries
- Plotly Python Open Source Graphing Library 3D Charts
- 3D Charts in Dash
Plotting Data Online via Plotly and Python
I don’t do a lot of plotting in my job, but I recently heard about a website called Plotly that provides a plotting service for anyone’s data. They even have a plotly package for Python (among others)! So in this article we will be learning how to plot with their package. Let’s have some fun making graphs!
Getting Started
You will need the plotly package to follow along with this article. You can use pip to get the package and install it:
Now that you have it installed, you’ll need to go to the Plotly website and create a free account. Once that’s done, you will get an API key. To make things super simple, you can use your username and API key to create a credentials file. Here’s how to do that:
import plotly.tools as tls tls.set_credentials_file( username="your_username", api_key="your_api_key") # to get your credentials credentials = tls.get_credentials_file()
If you don’t want to save your credentials, then you can also sign in to their service by doing the following:
import plotly.plotly as py py.sign_in('your_username','your_api_key')
For the purposes of this article, I’m assuming you have created the credentials file. I found that makes interacting with their service a bit easier to use.
Creating a Graph
Plotly seems to default to a Scatter Plot, so we’ll start with that. I decided to grab some data from a census website. You can download any US state’s population data, along with other pieces of data. In this case, I downloaded a CSV file that contained the population of each county in the state of Iowa. Let’s take a look:
import csv import plotly.plotly as py #---------------------------------------------------------------------- def plot_counties(csv_path): """ http://census.ire.org/data/bulkdata.html """ counties = <> county = [] pop = [] counter = 0 with open(csv_path) as csv_handler: reader = csv.reader(csv_handler) for row in reader: if counter == 0: counter += 1 continue county.append(row[8]) pop.append(row[9]) trace = dict(x=county, y=pop) data = [trace] py.plot(data, filename='ia_county_populations') if __name__ == '__main__': csv_path = 'ia_county_pop.csv' plot_counties(csv_path)
If you run this code, you should see a graph that looks like this:
You can also view the graph here. Anyway, as you can see in the code above, all I did was read the CSV file and extract out the county name and the population. Then I put that data into two different Python lists. Finally I created a dictionary of those lists and then wrapped that dictionary in a list. So you end up with a list that contains a dictionary that contains two lists! To make the Scatter Plot, I passed the data to plotly’s plot method.
Converting to a Bar Chart
Now let’s see if we can change the ScatterPlot to a Bar Chart. First off, we’ll play around with the plot data. The following was done via the Python interpreter:
>>> scatter = py.get_figure('driscollis', '0') >>> print scatter.to_string() Figure( data=Data([ Scatter( x=[u'Adair County', u'Adams County', u'Allamakee County', u'..', ], y=[u'7682', u'4029', u'14330', u'12887', u'6119', u'26076', '..' ] ) ]) )
This shows how we can grab the figure using the username and the plot’s unique number. Then we printed out the data structure. You will note that it doesn’t print out the entire data structure. Now let’s do the actual conversion to a Bar Chart:
from plotly.graph_objs import Data, Figure, Layout scatter_data = scatter.get_data() trace_bar = Bar(scatter_data[0]) data = Data([trace_bar]) layout = Layout(title="IA County Populations") fig = Figure(data=data, layout=layout) py.plot(fig, filename='bar_ia_county_pop')
This will create a bar chart at the following URL: https://plot.ly/~driscollis/1.
Here’s the image of the graph:
This code is slightly different than the code we used originally. In this case, we explicitly created a Bar object and passed it the scatter plot’s data. Then we put that data into a Data object. Next we created a Layout object and gave our chart a title. Then we created a Figure object using the data and layout objects. Finally we plotted the bar chart.
Saving the Graph to Disk
Plotly also allows you to save your graph to your hard drive. You can save it in the following formats: png, svg, jpeg, and pdf. Assuming you still have the Figure object from the previous example handy, you can do the following:
py.image.save_as(fig, filename='graph.png')
If you want to save using one of the other formats, then just use that format’s extension in the filename.
Wrapping Up
At this point you should be able to use the plotly package pretty well. There are many other graph types available, so be sure to read Plotly’s documentation thoroughly. They also support streaming graphs. As I understand it, Plotly allows you to create 10 graphs for free. After that you would either have to delete some of your graphs or pay a monthly fee.
Additional Reading
If you have question you can leave a comment below.
Mike Driscoll does not work or receive funding from any company or organization that would benefit from this article. Views expressed here are personal and not supported by university or company.
Online Matplotlib Compiler (Matplotlib 3.7.0)
Online Matplotlib Compiler (Matplotlib 3.7.0) helps you to Edit, Run and Share your Matplotlib Code directly from your browser. This development environment provides you version Matplotlib 3.7.0.
How to give program Input?
The latest version of Coding Ground allows to provide program input at run time from the termnial window exactly the same way as you run your program at your own computer. So simply run a program and provide your program input (if any) from the terminal window available in the right side.
Keyboard Shortcuts
Shortcut | Description |
---|---|
⌘ + Enter | Run the program |
⌘ + S | Save Project (Login Required) |
⇧ + ⌘ + S | Save As Project |
⌘ + P | New Project |
⌘ + G | Share Project |
⌘ + Z | Undo Editing |
⌘ + Y | Redo Editing |
⌘ + A | Select All Text |
⌘ + X | Cut Selected Text |
⌘ + C | Copy Selected Text |
⌘ + V | Paste Copied Text |
⌘ + F | Search Text |
⌘ + ⌥ + F | Replace Text |
Shortcut | Description |
---|---|
Ctrl + Enter | Run the program |
Ctrl + S | Save Project |
Shift + Ctrl + S | Save As Project |
Ctrl + G | Share Project |
Ctrl + Z | Undo Editing |
Ctrl + Y | Redo Editing |
Ctrl + A | Select All Text |
Ctrl + X | Cut Selected Text |
Ctrl + C | Copy Selected Text |
Ctrl + V | Paste Copied Text |
Ctrl + F | Search Text |
Ctrl + H | Replace Text |
Save Matplotlib Project
You can save your Matplotlib Project with us so that you can access this project later on. To save a project you will need to create a login Id with us. So before you save a project, please create a login Id using a link given at the top right corner of this page.
Share Matplotlib Project
You can use this feature to share your Matplotlib Code with your teachers, classmates and colleagues. Just click Share Button and it will create a short link, which can be shared through Email, WhatsApp or even through Social Media. A shared link will be deleted if it has been passive for almost 3 months.
Python Online Compiler
Write, Run & Share Python code online using OneCompiler’s Python online compiler for free. It’s one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler’s Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
Taking inputs (stdin)
OneCompiler’s python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys name = sys.stdin.readline() print("Hello "+ name)
About Python
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It’s is highly productive and efficient making it a very popular language.
Tutorial & Syntax help
Loops
1. If-Else:
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression #code elif conditional-expression #code else: #code
Note:
Indentation is very important in Python, make sure the indentation is followed correctly
2. For:
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
Example:
mylist=("Iphone","Pixel","Samsung") for i in mylist: print(i)
3. While:
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
Collections
There are four types of collections in Python.
1. List:
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
Example:
mylist=["iPhone","Pixel","Samsung"] print(mylist)
2. Tuple:
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
Example:
myTuple=("iPhone","Pixel","Samsung") print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung") print(myTuple) myTuple[1]="onePlus" print(myTuple)
3. Set:
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
Example:
4. Dictionary:
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key — value pairs.
Example:
Supported Libraries
Following are the libraries supported by OneCompiler’s Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
Matplotlib | Matplotlib is a cross-platform, data visualization and graphical plotting library for Python programming and it’s numerical mathematics extension NumPy |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |
Plotly Python Open Source Graphing Library 3D Charts
Plotly’s Python graphing library makes interactive, publication-quality graphs online. Examples of how to make 3D charts.
This page in another language
Deploy Python AI Dash apps on private Kubernetes clusters: Pricing | Demo | Overview | AI App Services
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
View Tutorial
3D Charts in Dash
Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash , click «Download» to get the code and run python app.py .
Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.