SlideShare a Scribd company logo
1 of 3
Download to read offline
# matplotlib demo from San Diego Python Data Analysis Workshop 20APR2013
# Drew Arnett
# a.arnett@ieee.org
# code from this file was copied and pasted in chunks to run
# import libraries that will be used
import matplotlib.mlab
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# read in the data set]
x = matplotlib.mlab.csv2rec("s_p_historical_closes.csv")
# plot closing data
plt.plot(x.date, x.close, ".")
plt.show()
# plot opening and closing data on one plot
plt.plot(x.date, x.open, ".", label="open")
plt.plot(x.date, x.close, ".", label="close")
plt.legend()
plt.show()
# that wasn't very interesting, so...
# plot daily range
plt.plot(x.date, x.high-x.low, ".")
plt.show()
# that isn't very fair, so...
# plot range scaled against close and in %
dailyrange = 100.*(x.high-x.low)/x.close
plt.plot(x.date, dailyrange, ".")
plt.show()
# use subplots to show more than one set of data at a time
# can also say subplot(6,1,1)
# subplot(number of subplot rows, number of subplot columns, specific subplot to
use)
plt.subplot(611)
plt.plot(x.date, x.open, ".", label="open")
plt.legend()
plt.subplot(612)
plt.plot(x.date, x.high, ".", label="high")
plt.legend()
plt.subplot(613)
plt.plot(x.date, x.low, ".", label="low")
plt.legend()
plt.subplot(614)
plt.plot(x.date, x.close, ".", label="close")
plt.legend()
plt.subplot(615)
plt.plot(x.date, x.volume, ".", label="volume")
plt.legend()
plt.subplot(616)
plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".", label="range")
plt.legend()
plt.show()
# the same thing, but more concise and maintainable code, perhaps a bit more
pythonic
for sub, item in enumerate("open,high,low,close,volume".split(",")):
plt.subplot(5,1,sub+1)
plt.plot(x.date, x[item], ".", label = item)
plt.legend(loc="best")
plt.show()
# all of that was not interactive, plot shown only on show()
# would like to see what happens with each plotting command
# so turn on interactive mode. this might be more useful for either
# interactive data analysis or refinement of a plot's formatting
plt.isinteractive()
plt.ion()
plt.subplot(211)
plt.plot(x.date, x.close, ".", label="close")
plt.subplot(212)
plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".", label="range")
plt.close()
plt.ioff()
# plot daily range to a file instead of interactive
plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".")
plt.title("S&P Daily range (% of close")
plt.xlabel("date")
plt.ylabel("%")
plt.savefig("snp range.png")
plt.show()
# plot numerous plots to a multipage PDF file
# obvious pros and cons to raster versus vector image file formats
pp = PdfPages("example.pdf")
for item in "open,high,low,close,volume".split(","):
plt.plot(x.date, x[item], ".", label = item)
plt.title(item)
plt.legend(loc="best")
pp.savefig()
plt.close()
pp.close()
# usually I'll use an image manipulation program to add annotation
# but matplotlib supports a lot of annotation and this could be very useful
# here the daily range is plotted with an annotation on the max point
dailyrange = 100.*(x.high-x.low)/x.close
peak = (x.date[dailyrange.argmax()], dailyrange[dailyrange.argmax()])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x.date, dailyrange, ".")
ax.annotate("WOW!", xy=peak, xytext = (peak[0], peak[1] + 3), arrowprops =
dict(facecolor = "black"))
plt.show()
# now two examples not using the S&P data set
# plotting two sets of data and with two scales for the vertical axis
data1 = [1,2,3,4,5,6,5,4,3,2,1]
data2 = [1,2,1,2,3,1,2,1,3,1,0]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(data1, color = "red")
ax1.set_ylabel("red")
ax2.plot(data2, color = "blue")
ax2.set_ylabel("blue")
plt.show()
# often I don't want autoscaling
# it may be good to assert to find situations where data exceeds a fixed scale
# and of course, now, the two scales are now the same and are redundant
# plotting the same two sets of data with fixed identical scales
data1 = [1,2,3,4,5,6,5,4,3,2,1]
data2 = [1,2,1,2,3,1,2,1,3,1,0]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(data1, color = "red")
ax1.set_ylabel("red")
ax1.set_ylim(0, 10)
ax2.plot(data2, color = "blue")
ax2.set_ylabel("blue")
ax2.set_ylim(0, 10)
plt.show()

More Related Content

What's hot

TF.data & Eager Execution
TF.data & Eager ExecutionTF.data & Eager Execution
TF.data & Eager ExecutionModulabs
 
tf.data: TensorFlow Input Pipeline
tf.data: TensorFlow Input Pipelinetf.data: TensorFlow Input Pipeline
tf.data: TensorFlow Input PipelineAlluxio, Inc.
 
D3 data, user, interaction
D3  data, user, interactionD3  data, user, interaction
D3 data, user, interactionDummas
 
Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked ListSayantan Sur
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2Aanand Singh
 
Chunked, dplyr for large text files
Chunked, dplyr for large text filesChunked, dplyr for large text files
Chunked, dplyr for large text filesEdwin de Jonge
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplifiedNaveenkumar Muguda
 
3. basic data structures(2)
3. basic data structures(2)3. basic data structures(2)
3. basic data structures(2)Hongjun Jang
 
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Windows Developer
 
The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018Lara Schenck
 
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...Lara Schenck
 
The Daily Method: JS Arrays::flatMap()
The Daily Method: JS Arrays::flatMap()The Daily Method: JS Arrays::flatMap()
The Daily Method: JS Arrays::flatMap()Lemuel Uhuru
 

What's hot (16)

TF.data & Eager Execution
TF.data & Eager ExecutionTF.data & Eager Execution
TF.data & Eager Execution
 
tf.data: TensorFlow Input Pipeline
tf.data: TensorFlow Input Pipelinetf.data: TensorFlow Input Pipeline
tf.data: TensorFlow Input Pipeline
 
Project gnuplot
Project gnuplotProject gnuplot
Project gnuplot
 
Python gis
Python gisPython gis
Python gis
 
D3 data, user, interaction
D3  data, user, interactionD3  data, user, interaction
D3 data, user, interaction
 
Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked List
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
 
R-Excel Integration
R-Excel IntegrationR-Excel Integration
R-Excel Integration
 
Chunked, dplyr for large text files
Chunked, dplyr for large text filesChunked, dplyr for large text files
Chunked, dplyr for large text files
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
 
3. basic data structures(2)
3. basic data structures(2)3. basic data structures(2)
3. basic data structures(2)
 
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
 
We Must Go Deeper
We Must Go DeeperWe Must Go Deeper
We Must Go Deeper
 
The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018
 
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
 
The Daily Method: JS Arrays::flatMap()
The Daily Method: JS Arrays::flatMap()The Daily Method: JS Arrays::flatMap()
The Daily Method: JS Arrays::flatMap()
 

Similar to Matplotlib demo code

R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemMaithreya Chakravarthula
 
Three Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataThree Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataDynamical Software, Inc.
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Djangokenluck2001
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions Dr. Volkan OBAN
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout source{d}
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePeter Solymos
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
PPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatrePPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatreRaginiRatre
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
5 R Tutorial Data Visualization
5 R Tutorial Data Visualization5 R Tutorial Data Visualization
5 R Tutorial Data VisualizationSakthi Dasans
 
Introduction to R for data science
Introduction to R for data scienceIntroduction to R for data science
Introduction to R for data scienceLong Nguyen
 
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017StampedeCon
 

Similar to Matplotlib demo code (20)

R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support System
 
Three Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataThree Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big Data
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Django
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
A Shiny Example-- R
A Shiny Example-- RA Shiny Example-- R
A Shiny Example-- R
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Matlab workshop
Matlab workshopMatlab workshop
Matlab workshop
 
PPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatrePPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini Ratre
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Day 3 plotting.pptx
Day 3   plotting.pptxDay 3   plotting.pptx
Day 3 plotting.pptx
 
5 R Tutorial Data Visualization
5 R Tutorial Data Visualization5 R Tutorial Data Visualization
5 R Tutorial Data Visualization
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Introduction to R for data science
Introduction to R for data scienceIntroduction to R for data science
Introduction to R for data science
 
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017
End-to-end Big Data Projects with Python - StampedeCon Big Data Conference 2017
 

More from pythonsd

Pep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in PythonPep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in Pythonpythonsd
 
Sqlalchemy lightning talk
Sqlalchemy lightning talkSqlalchemy lightning talk
Sqlalchemy lightning talkpythonsd
 
PythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development WorkshopPythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development Workshoppythonsd
 
Matplotlib presentation 20 apr2013 final
Matplotlib presentation 20 apr2013   finalMatplotlib presentation 20 apr2013   final
Matplotlib presentation 20 apr2013 finalpythonsd
 
Blaze the-evolution-of-numpy
Blaze the-evolution-of-numpyBlaze the-evolution-of-numpy
Blaze the-evolution-of-numpypythonsd
 
Django production
Django productionDjango production
Django productionpythonsd
 
Django Toolbox
Django ToolboxDjango Toolbox
Django Toolboxpythonsd
 
Why Python 3
Why Python 3Why Python 3
Why Python 3pythonsd
 

More from pythonsd (8)

Pep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in PythonPep 465 - Matrix Multiplication in Python
Pep 465 - Matrix Multiplication in Python
 
Sqlalchemy lightning talk
Sqlalchemy lightning talkSqlalchemy lightning talk
Sqlalchemy lightning talk
 
PythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development WorkshopPythonSD Test Driven Django Development Workshop
PythonSD Test Driven Django Development Workshop
 
Matplotlib presentation 20 apr2013 final
Matplotlib presentation 20 apr2013   finalMatplotlib presentation 20 apr2013   final
Matplotlib presentation 20 apr2013 final
 
Blaze the-evolution-of-numpy
Blaze the-evolution-of-numpyBlaze the-evolution-of-numpy
Blaze the-evolution-of-numpy
 
Django production
Django productionDjango production
Django production
 
Django Toolbox
Django ToolboxDjango Toolbox
Django Toolbox
 
Why Python 3
Why Python 3Why Python 3
Why Python 3
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Matplotlib demo code

  • 1. # matplotlib demo from San Diego Python Data Analysis Workshop 20APR2013 # Drew Arnett # a.arnett@ieee.org # code from this file was copied and pasted in chunks to run # import libraries that will be used import matplotlib.mlab import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages # read in the data set] x = matplotlib.mlab.csv2rec("s_p_historical_closes.csv") # plot closing data plt.plot(x.date, x.close, ".") plt.show() # plot opening and closing data on one plot plt.plot(x.date, x.open, ".", label="open") plt.plot(x.date, x.close, ".", label="close") plt.legend() plt.show() # that wasn't very interesting, so... # plot daily range plt.plot(x.date, x.high-x.low, ".") plt.show() # that isn't very fair, so... # plot range scaled against close and in % dailyrange = 100.*(x.high-x.low)/x.close plt.plot(x.date, dailyrange, ".") plt.show() # use subplots to show more than one set of data at a time # can also say subplot(6,1,1) # subplot(number of subplot rows, number of subplot columns, specific subplot to use) plt.subplot(611) plt.plot(x.date, x.open, ".", label="open") plt.legend() plt.subplot(612) plt.plot(x.date, x.high, ".", label="high") plt.legend() plt.subplot(613) plt.plot(x.date, x.low, ".", label="low") plt.legend() plt.subplot(614) plt.plot(x.date, x.close, ".", label="close")
  • 2. plt.legend() plt.subplot(615) plt.plot(x.date, x.volume, ".", label="volume") plt.legend() plt.subplot(616) plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".", label="range") plt.legend() plt.show() # the same thing, but more concise and maintainable code, perhaps a bit more pythonic for sub, item in enumerate("open,high,low,close,volume".split(",")): plt.subplot(5,1,sub+1) plt.plot(x.date, x[item], ".", label = item) plt.legend(loc="best") plt.show() # all of that was not interactive, plot shown only on show() # would like to see what happens with each plotting command # so turn on interactive mode. this might be more useful for either # interactive data analysis or refinement of a plot's formatting plt.isinteractive() plt.ion() plt.subplot(211) plt.plot(x.date, x.close, ".", label="close") plt.subplot(212) plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".", label="range") plt.close() plt.ioff() # plot daily range to a file instead of interactive plt.plot(x.date, 100.*(x.high-x.low)/x.close, ".") plt.title("S&P Daily range (% of close") plt.xlabel("date") plt.ylabel("%") plt.savefig("snp range.png") plt.show() # plot numerous plots to a multipage PDF file # obvious pros and cons to raster versus vector image file formats pp = PdfPages("example.pdf") for item in "open,high,low,close,volume".split(","): plt.plot(x.date, x[item], ".", label = item) plt.title(item) plt.legend(loc="best") pp.savefig()
  • 3. plt.close() pp.close() # usually I'll use an image manipulation program to add annotation # but matplotlib supports a lot of annotation and this could be very useful # here the daily range is plotted with an annotation on the max point dailyrange = 100.*(x.high-x.low)/x.close peak = (x.date[dailyrange.argmax()], dailyrange[dailyrange.argmax()]) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x.date, dailyrange, ".") ax.annotate("WOW!", xy=peak, xytext = (peak[0], peak[1] + 3), arrowprops = dict(facecolor = "black")) plt.show() # now two examples not using the S&P data set # plotting two sets of data and with two scales for the vertical axis data1 = [1,2,3,4,5,6,5,4,3,2,1] data2 = [1,2,1,2,3,1,2,1,3,1,0] fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twinx() ax1.plot(data1, color = "red") ax1.set_ylabel("red") ax2.plot(data2, color = "blue") ax2.set_ylabel("blue") plt.show() # often I don't want autoscaling # it may be good to assert to find situations where data exceeds a fixed scale # and of course, now, the two scales are now the same and are redundant # plotting the same two sets of data with fixed identical scales data1 = [1,2,3,4,5,6,5,4,3,2,1] data2 = [1,2,1,2,3,1,2,1,3,1,0] fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twinx() ax1.plot(data1, color = "red") ax1.set_ylabel("red") ax1.set_ylim(0, 10) ax2.plot(data2, color = "blue") ax2.set_ylabel("blue") ax2.set_ylim(0, 10) plt.show()