PyPlot.jl examples

From the extensive examples by gizmaa:

https://gist.github.com/gizmaa/7214002

Annotations

using PyPlot
using Dates
######################################
#  Generate an hour of data at 10Hz  #
######################################
# Generate time array
x = collect(DateTime(2013,10,4):Dates.Millisecond(100):DateTime(2013,10,4,1)) 
# Convert time from milliseconds from day 0 to days from day 0
x = Dates.value.(x)/1000/60/60/24 
y = sin.(2*pi*collect(0:2*pi/(length(x)+1):2*pi-(2*pi/length(x))))
dx = maximum(x) - minimum(x)
dy = maximum(y) - minimum(y)
y2 = 30.0*(1.0 .+ sin.(2.0*pi*collect(pi:2.0*pi/length(x):3*pi-(2*pi/length(x))))) .- 10.0
x2 = collect(minimum(x):dx/20:maximum(x))
y2 = 10rand(21) .- 3
x3 = collect(minimum(x):dx/20:maximum(x))
y3 = 10rand(21) .- 3
##########
#  Plot  #
##########
fig, ax = subplots(figsize=(10,10)) # Create a figure and save its handle
# Plot a basic line
p = plot_date(x,y,linestyle="-",marker="None",label="Test Plot") 
# Fit the axis tightly to the plot
PyPlot.axis("tight") 
PyPlot.title("U Component of Wind")
PyPlot.grid("on")
# Create a legend of all the existing plots using their labels as names
PyPlot.legend(loc="upper right",fancybox="true") 
##################
#  Text Styling  #
##################
font1 = Dict("family"=>"serif",
             "color"=>"darkred",
             "weight"=>"normal",
             "size"=>16)
xlabel("Time",fontdict=font1)
ylabel("Velocity (m/s)")
setp(ax.get_yticklabels(),fontsize=24,color="blue") # Y Axis font formatting
#################
#  Arrow Tests  #
#################
# This arrows orient toward the x-axis, the more horizontal they are the more skewed they look
arrow(x[convert(Int64,floor(length(x)/2))],
	    0.4,
	    0.0009,
	    0.4,
	    head_width=0.001,
	    width=0.00015,
	    head_length=0.07,
	    overhang=0.5,
	    head_starts_at_zero="true",
	    facecolor="red")
arrow(x[convert(Int64,floor(0.3length(x)))]-0.25dx,
	    y[convert(Int64,floor(0.3length(y)))]+0.25dy,
	    0.25dx,
	    -0.25dy,
	    head_width=0.001,
	    width=0.00015,
	    head_length=0.07,
	    overhang=0.5,
	    head_starts_at_zero="true",
	    facecolor="red",
	    length_includes_head="true")
###########################
#  Text Annotation Tests  #
###########################
# Julia dictionary objects are automatically converted to Python object when they pass into a PyPlot function
annotate("Look, data!",
	xy=[x[convert(Int64,floor(length(x)/4.1))];y[convert(Int64,floor(length(y)/4.1))]],
	xytext=[x[convert(Int64,floor(length(x)/4.1))]+0.1dx;y[convert(Int64,floor(length(y)/4.1))]+0.1dy],
	xycoords="data",
	arrowprops=Dict("facecolor"=>"black"))
annotate("Figure Top Right",
	xy=[1;1],
	xycoords="figure fraction",
	xytext=[0,0],
	textcoords="offset points",
	ha="right",
	va="top")
annotate(L"$\int x = \frac{x^2}{2} + C$",
	xy=[1;0],
	xycoords="axes fraction",
	xytext=[-10,10],
	textcoords="offset points",
	fontsize=30.0,
	ha="right",
	va="bottom")
fig.autofmt_xdate(bottom=0.2,rotation=30,ha="right")
fig.canvas.draw() # Update the figure
fig
2.0s

The following command will point an arrow at a point and label the arrow.

annotate("Look, data!",
	 xy=[x;y,# Arrow tip
	 xytext=[x+dx;y+dy], # Text offset from tip
	 xycoords="data", # Coordinates in in "data" units
	 arrowprops=["facecolor"=>"black"]) # Julia dictionary objects are automatically converted to Python object when they pass into a PyPlot function
Julia

It's important to note that in Python the arrowprops would look like this: arrowprops=dict(arrowstyle="->"). Dictionary definitions look like arrowprops=["facecolor"=>"black"] in Julia.

LaTeX can be used by putting an L in front of LaTeX code, L"$\int x = \frac{x^2}{2} + C$".

annotate(L"$\int x = \frac{x^2}{2} + C$",
	xy=[1;0],
	xycoords="axes fraction",
	xytext=[-10,10],
	textcoords="offset points",
	fontsize=30.0,
	ha="right",
	va="bottom")
Julia

Axis Placement

ax.spines["top"].set_visible(false) # Hide the top edge of the axis
ax.spines["right"].set_visible(false) # Hide the right edge of the axis
ax.spines["left"].set_position("center") # Move the right axis to the center
ax.spines["bottom"].set_position("center") # Most the bottom axis to the center
ax.xaxis.set_ticks_position("bottom") # Set the x-ticks to only the bottom
ax.yaxis.set_ticks_position("left") # Set the y-ticks to only the left
Julia
ax2.spines["top"].set_visible(false) # Hide the top edge of the axis
ax2.spines["right"].set_visible(false) # Hide the right edge of the axis
ax2.xaxis.set_ticks_position("bottom")
ax2.yaxis.set_ticks_position("left")
ax2.spines["left"].set_position(("axes",-0.03)) # Offset the left scale from the axis
ax2.spines["bottom"].set_position(("axes",-0.05)) # Offset the bottom scale from the axis
Julia
using PyPlot
###################
#  Generate Data  #
###################
x = collect(0:pi/50:2pi)
y = sin.(x)
###############
#  Plot Data  #
###############
fig, (ax1, ax2) = PyPlot.subplots(nrows=2, figsize=(10,10))
ax1.plot(x,y)
PyPlot.axis("tight")
ax1.spines["top"].set_visible(false) # Hide the top edge of the axis
ax1.spines["right"].set_visible(false) # Hide the right edge of the axis
ax1.spines["left"].set_position("center") # Move the right axis to the center
ax1.spines["bottom"].set_position("center") # Most the bottom axis to the center
#ax.spines["left"].set_smart_bounds(true)
ax1.xaxis.set_ticks_position("bottom") # Set the x-ticks to only the bottom
ax1.yaxis.set_ticks_position("left") # Set the y-ticks to only the left
ax2.plot(x,y)
PyPlot.axis("tight")
ax2.spines["top"].set_visible(false) # Hide the top edge of the axis
ax2.spines["right"].set_visible(false) # Hide the right edge of the axis
ax2.xaxis.set_ticks_position("bottom")
ax2.yaxis.set_ticks_position("left")
ax2.spines["left"].set_position(("axes",-0.03)) # Offset the left scale from the axis
ax2.spines["bottom"].set_position(("axes",-0.05)) # Offset the bottom scale from the axis
ax2.set_xlabel("X Axis")
ax2.set_ylabel("Y Axis")
PyPlot.suptitle("Axis Placement")
fig
0.8s

Bar Plot

b = bar(x,y,color="#0f87bf",align="center",alpha=0.4)
Julia
b = barh(x,y,color="#0f87bf",align="center",alpha=0.4)
Julia
using PyPlot
#################
#  Create Data  #
#################
x = [1:1:50;]
y = 100*rand(50);
################
##  Bar Plot  ##
################
fig, (ax1, ax2) = PyPlot.subplots(nrows=2, figsize=(10,10))
ax1.bar(x,y,color="#0f87bf",align="center",alpha=0.4)
ax1.axis("tight")
ax1.set_title("Vertical Bar Plot")
ax1.grid(true)
ax1.set_xlabel("X")
ax1.set_ylabel("Y")
ax2.barh(x,y,color="#0f87bf",align="center",alpha=0.4)
ax2.axis("tight")
ax2.set_title("Horizontal Bar Plot")
ax2.grid(true)
ax2.set_xlabel("X")
ax2.set_ylabel("Y")
PyPlot.suptitle("Bar Plot Examples")
fig
1.8s

Box Plot

boxplot(data,        # Each column/cell is one box
	      notch=true,  # Notched center
	      whis=0.75,   # Whisker length as a percent of inner quartile range
	      widths=0.25, # Width of boxes
	      vert=false,  # Horizontal boxes
	      sym="rs")    # Symbol color and shape (rs = red square)
Julia
using PyPlot
# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
# http://matplotlib.org/examples/pylab_examples/boxplot_demo.html
###################
##  Create Data  ##
###################
# Boxes with irregular amounts of data can
# be plotted by putting the data into bins in an ANY array.
num = 5
# Preallocate an ANY array for the storage of final values
data = Array{Any}(undef,num) 
for i=1:num
	num1 = round.(40rand(1)) .+ 10
	num1 = Int(num1[1])
	num2 = round.(20rand(1)) .+ 10
	num2 = Int(num2[1])
	num3 = round.(10rand(1)) .+ 1
	num3 = Int(num3[1])
	num4 = round.(10rand(1)) .+ 1
	num4 = Int(num4[1])
	
	spread = 100rand(num1)
	center = 50rand(num2)
	flier_high = 100rand(num3) .+ 100
	flier_low = -100rand(num4)
	data[i] = [spread;center;flier_high;flier_low]
end
################
##  Box Plot  ##
################
fig, axs = PyPlot.subplots(2, 2, figsize=(10,10))
axs[1].boxplot(data) # Basic
axs[3].boxplot(data,true)
axs[2].boxplot(data,false,"gD") # (gD = green diamond)
axs[4].boxplot(data, # Each column/cell is one box
	             notch=true,  # Notched center
	             whis=0.75,   # Whisker length as a percent of inner quartile range
	             widths=0.25, # Width of boxes
	             vert=false,  # Horizontal boxes
	             sym="rs")    # Symbol color and shape (rs = red square)
suptitle("Box Plot Examples")
gcf()
1.8s

Broken Axis Subplot

# Reference: https://gist.github.com/gizmaa/7214002#gistcomment-2831191
using Pkg
Pkg.add("PyCall")
using PyPlot, PyCall
axes_grid1 = pyimport("mpl_toolkits.axes_grid1")
###################
##  Create Data  ##
###################
x = rand(100)
y = rand(100)
y2 = rand(100).+10
##########################
##  First (Upper) Plot  ##
##########################
fig, axes = subplots(nrows=2, sharex=true, figsize=(10,10))
ax = axes[1]
divider = axes_grid1.make_axes_locatable(ax)
ax2 = divider.new_vertical(size="100%", pad=0.1)
fig.add_axes(ax2)
# Lower Portion of First Plot
ax.scatter(x, y)
ax.set_ylim(0, 1)
ax.spines["top"].set_visible(false)
# Upper Portion of First Plot
ax2.scatter(x, y2)
ax2.set_ylim(10, 11)
ax2.tick_params(bottom="off", labelbottom="off")
ax2.spines["bottom"].set_visible(false)
###############################
##  Add Line Break Markings  ##
###############################
# From https://matplotlib.org/examples/pylab_examples/broken_axis.html
# Upper Line Break Markings
d = 0.015  # how big to make the diagonal lines in axes coordinates
ax2.plot((-d, +d), (-d, +d), transform=ax2.transAxes, color="k", clip_on=false,linewidth=0.8)        # Left diagonal
ax2.plot((1 - d, 1 + d), (-d, +d), transform=ax2.transAxes, color="k", clip_on=false,linewidth=0.8)  # Right diagonal
# Lower Line Break Markings
ax.plot((-d, +d), (1 - d, 1 + d), transform=ax.transAxes, color="k", clip_on=false,linewidth=0.8)  # Left diagonal
ax.plot((1 - d, 1 + d), (1 - d, 1 + d), transform=ax.transAxes, color="k", clip_on=false,linewidth=0.8)  # Right diagonal
###################
##  Second Plot  ##
###################
axes[2].scatter(x, y)
gcf()
33.4s

Custom Time

The formatting preparation is accomplished by calling the formatters within Matplotlib.

majorformatter = matplotlib.dates.DateFormatter("%d.%m.%Y")
minorformatter = matplotlib.dates.DateFormatter("%H:%M")
majorlocator = matplotlib.dates.DayLocator(interval=1)
minorlocator = matplotlib.dates.HourLocator(byhour=(8, 16))
Julia

They are then applied to the specific axis, the handle of which is called ax1 in this case.

ax1.xaxis.set_major_formatter(majorformatter)
ax1.xaxis.set_minor_formatter(minorformatter)
ax1.xaxis.set_major_locator(majorlocator)
ax1.xaxis.set_minor_locator(minorlocator)
Julia

using PyPlot
using Dates
###################
##  Create Data  ##
###################
dt = Dates.Hour(1)
time = collect(DateTime(2014,11,20):dt:DateTime(2014,11,22))
y = 10rand(length(time))
#y = floor(100*rand(length(time))) # Fails unless the time span is very short
dfmt = Dates.DateFormat("yyyy-mm-dd HH:MM:SS")
font1 = Dict("fontname"=>"Sans","style"=>"normal")
time2 = Dates.value.(time)/1000/60/60/24 # Convert time from milliseconds from day 0 to days from day 0
timespan = "\n" * Dates.format(minimum(time),dfmt) * " - " * Dates.format(maximum(time),dfmt)
majorformatter = matplotlib.dates.DateFormatter("%d.%m.%Y")
minorformatter = matplotlib.dates.DateFormatter("%H:%M")
majorlocator = matplotlib.dates.DayLocator(interval=1)
minorlocator = matplotlib.dates.HourLocator(byhour=(8, 16))
############
##  Plot  ##
############
# Create a figure and save the handle
fig, ax1 = subplots(figsize=(12,12)) 
p1 = ax1.plot_date(time2,y,linestyle="-",marker="None",label="test")
ax1.axis("tight")
ax1.set_title("Random Data Against Time\n" * timespan)
ax1.grid(true)
ax1.set_xlabel("Time")
ax1.set_ylabel("Stuff",fontdict=font1)
ax1.xaxis.set_major_formatter(majorformatter)
ax1.xaxis.set_minor_formatter(minorformatter)
ax1.xaxis.set_major_locator(majorlocator)
ax1.xaxis.set_minor_locator(minorlocator)
fig.autofmt_xdate(bottom=0.2,rotation=30,ha="right")
fig.canvas.draw() # Update the figure
PyPlot.tight_layout()
gcf()
2.4s

Error Bar

errorbar(x, # Original x data points, N values
	       y, # Original y data points, N values
	       yerr=errs, # Plus/minus error ranges, Nx2 values
	       fmt="o") # Format
Julia
using PyPlot
###################################
#  Generate a few points of data  #
###################################
x = collect(DateTime(2013,10,4):Dates.Day(1):DateTime(2013,10,9))
y = [0.9;0.75;0.5;0.4;0.35;0.3]
uppererror = [0.05 0.05 0.05 0.03 0.15 0.05;]
lowererror = [0.15 0.2 0.05 0.1 0.05 0.05;]
errs = [lowererror;uppererror]
println("From " * string(x[1]) * " to " * string(x[end]))
x = Dates.value.(x)/1000/60/60/24 # Convert time from milliseconds from day 0 to days from day 0
##########
#  Plot  #
##########
fig, ax = subplots(figsize=(10,10)) # Create a new figure
p = ax.plot_date(x,y,linestyle="-",marker="None",label="Base Plot") # Basic line plot
pe = ax.errorbar(x,y,yerr=errs,fmt="o") # Plot irregular error bars
ax.axis("tight")
ax.set_title("Error Bar Example")
ax.set_xlabel("Time")
ax.set_ylabel("Some Data")
ax.grid(true)
fig.autofmt_xdate(bottom=0.2,rotation=30,ha="right") # Autoformat the time format and rotate the labels so they don't overlap
fig.canvas.draw() # Update the figure
gcf()
1.9s

Histogram

h = plt.hist(x,nbins) # Histogram, PyPlot.plt required to differentiate with conflicting hist command
Julia
using PyPlot
#################
#  Create Data  #
#################
x = randn(1000) # Values
nbins = 50 # Number of bins
##########
#  Plot  #
##########
fig, ax = subplots(figsize=(10,10)) # Not strictly required
h = ax.hist(x,nbins) # Histogram
ax.grid("on")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Histogram")
gcf()
1.7s

Line collections

# Reference: David P. Sanders - 
# https://groups.google.com/d/msg/julia-users/BGcEOZVw8YU/Oacy1O5zBQAJ
using PyPlot
####################
##  Prepare Data  ##
####################
# lines = Any array of tuples of floating point pairs
# First Segment Group
xs = [1.,3.,5.,0.]
ys = [2.,4.,.06,0.]
lines = Any[collect(zip(xs,ys))]
# lines = [(1.0,2.0),(3.0,4.0),(5.0,0.06),(0.0,0.0)]
# Second Segment Group
xs = [3.,4]
ys = [5.,6]
push!(lines,collect(zip(xs,ys)))
# Third Segment Group
xs = [8.,2]
ys = [2.,4]
push!(lines,collect(zip(xs,ys)))
##############
##  Colors  ##
##############
# Line segments will be plotted with the following order of colors and will
# cycle back to the beginning of the array when it has gone through all of them
c = Vector{Int}[[1,0,0],[0,1,0],[0,0,1]]
# Assemble everything into a LineCollection
line_segments = matplotlib.collections.LineCollection(lines,colors=c)
############
##  Plot  ##
############
fig, ax = subplots(figsize=(10,10))
ax.add_collection(line_segments)
ax.axis("image")
ax.axis("tight")
gcf()
1.0s

Major and minor ticks

###########################
#  Set the tick interval  #
###########################
Mx = matplotlib.ticker.MultipleLocator(20) # Define interval of major ticks
f = matplotlib.ticker.FormatStrFormatter("%1.2f") # Define format of tick labels
ax.xaxis.set_major_locator(Mx) # Set interval of major ticks
ax.xaxis.set_major_formatter(f) # Set format of tick labels
mx = matplotlib.ticker.MultipleLocator(5) # Define interval of minor ticks
ax.xaxis.set_minor_locator(mx) # Set interval of minor ticks
My = matplotlib.ticker.MultipleLocator(0.5) # Define interval of major ticks
ax.yaxis.set_major_locator(My) # Set interval of major ticks
my = matplotlib.ticker.MultipleLocator(0.1) # Define interval of minor ticks
ax.yaxis.set_minor_locator(my) # Set interval of minor ticks
#########################
#  Set tick dimensions  #
#########################
ax.xaxis.set_tick_params(which="major",length=10,width=2,labelsize=16)
ax.xaxis.set_tick_params(which="minor",length=5,width=2)
fig.canvas.draw() # Update the figure
Julia
using PyPlot
###################
#  Generate Data  #
###################
x = 0.0:0.01:100.0
y = @. sin(0.1pi*x)*exp(-0.01x)
##########
#  Plot  #
##########
fig, ax = subplots(figsize=(10,10))
p = ax.plot(x,y)
ax.set(xlabel="X Axis", ylabel="Y Axis", title="Major and Minor Ticks")
ax.grid("on")
###########################
#  Set the tick interval  #
###########################
Mx = matplotlib.ticker.MultipleLocator(20) # Define interval of major ticks
f = matplotlib.ticker.FormatStrFormatter("%1.2f") # Define format of tick labels
ax.xaxis.set_major_locator(Mx) # Set interval of major ticks
ax.xaxis.set_major_formatter(f) # Set format of tick labels
mx = matplotlib.ticker.MultipleLocator(5) # Define interval of minor ticks
ax.xaxis.set_minor_locator(mx) # Set interval of minor ticks
My = matplotlib.ticker.MultipleLocator(0.5) # Define interval of major ticks
ax.yaxis.set_major_locator(My) # Set interval of major ticks
my = matplotlib.ticker.MultipleLocator(0.1) # Define interval of minor ticks
ax.yaxis.set_minor_locator(my) # Set interval of minor ticks
#########################
#  Set tick dimensions  #
#########################
ax.xaxis.set_tick_params(which="major",length=10,width=2,labelsize=16)
ax.xaxis.set_tick_params(which="minor",length=5,width=2)
fig.canvas.draw() # Update the figure
gcf()
1.8s

Multiple overlapping axes

using PyPlot
###################
##  Create Data  ##
###################
n = 15 # Number of values
x = collect(1:n)
y1 = 10rand(n,1) .- 2
y2 = 1000rand(n,1)
y3 = 30rand(n,1) .- 15
##########
#  Plot  #
##########
fig, ax = subplots(figsize=(10,10))
p = ax.plot(x,y1,linestyle="-",marker="o",label="First") # Plot a basic line
ax.set(title="Multi-axis Plot", xlabel="X Axis")
ax.set_ylabel("Left Axis",fontdict=font1)
setp(ax.get_yticklabels(),color="blue") # Y Axis font formatting
################
#  Other Axes  #
################
new_position = [0.06;0.06;0.77;0.91] # Position Method 2
ax.set_position(new_position) # Position Method 2: Change the size and position of the axis
#fig.subplots_adjust(right=0.85) # Position Method 1
ax2 = ax.twinx() # Create another axis on top of the current axis
font2 = Dict("color"=>"purple")
ax2.set_ylabel("Right Axis",fontdict=font2)
p = ax2.plot(x,y2,color="purple",linestyle="-",marker="o",label="Second") # Plot a basic line
ax2.set_position(new_position) # Position Method 2
setp(ax2.get_yticklabels(),color="purple") # Y Axis font formatting
ax3 = ax.twinx() # Create another axis on top of the current axis
ax3.spines["right"].set_position(("axes",1.12)) # Offset the y-axis label from the axis itself so it doesn't overlap the second axis
font3 = Dict("color"=>"green")
ax3.set_ylabel("Far Right Axis",fontdict=font3)
p = ax3.plot(x,y3,color="green",linestyle="-",marker="o",label="Third") # Plot a basic line
ax3.set_position(new_position) # Position Method 2
setp(ax.get_yticklabels(),color="green") # Y Axis font formatting
axis("tight")
# Enable just the right part of the frame
ax3.set_frame_on(true) # Make the entire frame visible
ax3.patch.set_visible(false) # Make the patch (background) invisible so it doesn't cover up the other axes' plots
ax3.spines["top"].set_visible(false) # Hide the top edge of the axis
ax3.spines["bottom"].set_visible(false) # Hide the bottom edge of the axis
fig.canvas.draw() # Update the figure
gcf()
2.0s

Pie charts

p = pie(sizes,
        labels=labels,
        shadow=true,
        startangle=90,
        explode=explode,
        colors=colors,
        autopct="%1.1f%%",
        textprops=font)
Julia
using PyPlot
#################
#  Create Data  #
#################
labels = ["Lager";"Pilsner";"Stout";"IPA"]
colors = ["yellowgreen";"gold";"lightskyblue";"lightcoral"]
sizes = [15; 30; 45; 10]
explode = zeros(length(sizes))
explode[2] = 0.1 # Move slice 2 out by 0.1
font = Dict("fontname"=>"Sans","weight"=>"semibold")
###############
#  Pie Chart  #
###############
fig = figure(figsize=(10,10))
p = pie(sizes,
		labels=labels,
		shadow=true,
		startangle=90,
		explode=explode,
		colors=colors,
		autopct="%1.1f%%",
		textprops=font)
axis("equal")
title("Beer")
gcf()
1.1s

Quiver Plots

q = quiver(X,Y,U,V)
ax = gca()
ax.quiverkey(q,X=0.07,Y = 0.05, U = 10,coordinates="figure", label="Quiver key, length = 10",labelpos = "E")
Julia
# http://matplotlib.org/gallery/images_contours_and_fields/quiver_simple_demo.html#sphx-glr-gallery-images-contours-and-fields-quiver-simple-demo-py
# Note: See the following link for more information on the quiverkey parameters
#	http://matplotlib.org/api/_as_gen/matplotlib.pyplot.quiverkey.html?highlight=quiverkey#matplotlib.pyplot.quiverkey
using PyPlot
###################
##  Create Data  ##
###################
R = -10:1:9
X = [R;]'
Y = [R;]'
U = repeat([R;]',length(X))
V = repeat([R;],1,length(Y))
###################
##  Quiver Plot  ##
###################
fig, ax = subplots(figsize=(10,10))
q = ax.quiver(X,Y,U,V)
ax.quiverkey(q,X=0.07,Y = 0.05, U = 10,coordinates="figure", label="Quiver key, length = 10",labelpos = "E")
ax.set_title("Quiver Plot Example")
gcf()
1.4s

Scatter plots

scatter(x,y,s=areas,alpha=0.5)
Julia
using PyPlot
#################
#  Create Data  #
#################
x = 100*rand(50)
y = 100*rand(50)
areas = 800*rand(50)
##################
#  Scatter Plot  #
##################
fig, ax = subplots(figsize=(10,10))
ax.scatter(x,y,s=areas,alpha=0.5)
ax.set(title="Scatter Plot", xlabel="X", ylabel="Y")
ax.grid(true)
gcf()
1.3s

Stream Plots

streamplot(X,Y,U,V)
Julia
streamplot(X,Y,U,V,color=U,linewidth=2,cmap=PyPlot.cm[:autumn])
Julia
lw = 5 .* speed ./ maximum(speed) # Line Widths
streamplot(X,Y,U,V,density=0.6,color="k",linewidth=lw)
Julia
using PyPlot
# http://matplotlib.org/examples/images_contours_and_fields/streamplot_demo_features.html
###################
##  Create Data  ##
###################
minval = -3
maxval = 3
steps = 100
X = repeat(range(minval,stop=maxval,length=steps)',steps)
Y = repeat(range(minval,stop=maxval,length=steps),1,steps)
U = -1 .- X.^2 .+ Y
V = 1 .+ X .- Y.^2
speed = sqrt.(U.^2 .+ V.^2)
####################
##  Stream Plots  ##
####################
fig, axs = subplots(nrows=3, figsize=(10,10))
axs[1].streamplot(X,Y,U,V)
axs[2].streamplot(X,Y,U,V,color=U,linewidth=2,cmap=PyPlot.cm.autumn)
lw = 5 .* speed ./ maximum(speed) # Line Widths
axs[3].streamplot(X,Y,U,V,density=0.6,color="k",linewidth=lw)
suptitle("Stream Plot Examples")
gcf()
4.6s

Subplots

subplot(YXN), Y = number of columns, X = number of rows, N = number of axis being created

The number, N, of a grid of axes starts in the upper left (1), and goes right then down. The second axis of a 2x2 grid is the upper right axis.

subplot(313) # Create the third plot of a 3x1 group of subplots
suptitle("3x1 Subplot") # Supe title, title for all subplots combined
Julia

subplots(): A object-oriented way of drawing subplots, with less confusion

using PyPlot
#####################
##  2x2 Plot Grid  ##
#####################
fig = figure("pyplot_subplot_mixed",figsize=(10,10)) # Create a new blank figure
#fig.set_figheight(7) # Doesn't work
#fig.set_figwidth(3) # Doesn't work
subplot(221) # Create the 1st axis of a 2x2 arrax of axes
grid("on") # Create a grid on the axis
PyPlot.title("221") # Give the most recent axis a title
subplot(222,polar="true") # Create a plot and make it a polar plot, 2nd axis of 2x2 axis grid
PyPlot.title("222")
ax = subplot(223,polar="true") # Create a plot and make it a polar plot, 3rd axis of 2x2 axis grid
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot
ax.set_theta_direction(-1) # Switch the polar plot to clockwise
PyPlot.title("223")
subplot(224) # Create the 4th axis of a 2x2 arrax of axes
xlabel("This is an X axis")
ylabel("This is a y axis")
PyPlot.title("224")
fig.canvas.draw() # Update the figure
suptitle("2x2 Subplot")
gcf()
1.5s
###################
##  Column Plot  ##
###################
fig = figure("pyplot_subplot_column",figsize=(10,10))
subplot(311) # Create the 1st axis of a 3x1 array of axes
PyPlot.title("311")
subplot(312) # Create the 2nd axis of a 3x1 arrax of axes
ax = gca() # Get the handle of the current axis
ax.set_yscale("log") # Set the y axis to a logarithmic scale
grid("on")
ylabel("Log Scale")
PyPlot.title("312")
subplot(313) # Create the 3rd axis of a 3x1 array of axes
ax = gca()
ax.set_xscale("log") # Set the x axis to a logarithmic scale
xlabel("Log Scale")
PyPlot.title("313")
fig.canvas.draw() # Update the figure
suptitle("3x1 Subplot")
gcf() # Needed for IJulia to plot inline
1.6s
###################
##  Shared Axis  ##
###################
fig = figure("pyplot_subplot_touching",figsize=(10,10))
subplots_adjust(hspace=0.0) # Set the vertical spacing between axes
subplot(311) # Create the 1st axis of a 3x1 array of axes
ax1 = gca()
ax1.set_xscale("log") # Set the x axis to a logarithmic scale
setp(ax1.get_xticklabels(),visible=false) # Disable x tick labels
grid("on")
PyPlot.title("Title")
yticks(0.1:0.2:0.9) # Set the y-tick range and step size, 0.1 to 0.9 in increments of 0.2
ylim(0.0,1.0) # Set the y-limits from 0.0 to 1.0
subplot(312,sharex=ax1) # Create the 2nd axis of a 3x1 array of axes
ax2 = gca()
ax2.set_xscale("log") # Set the x axis to a logarithmic scale
setp(ax2.get_xticklabels(),visible=false) # Disable x tick labels
grid("on")
ylabel("Log Scale")
yticks(0.1:0.2:0.9)
ylim(0.0,1.0)
subplot(313,sharex=ax2) # Create the 3rd axis of a 3x1 array of axes
ax3 = gca()
ax3.set_xscale("log") # Set the x axis to a logarithmic scale
grid("on")
xlabel("Log Scale")
yticks(0.1:0.2:0.9)
ylim(0.0,1.0)
fig.canvas.draw() # Update the figure
suptitle("3x1 Shared Axis")
gcf() # Needed for IJulia to plot inline
2.4s

Surface Plot

plot_surface(xgrid, ygrid, z, rstride=2,edgecolors="k", cstride=2,
   cmap=ColorMap("gray"), alpha=0.8, linewidth=0.25)
Julia
contour(xgrid, ygrid, z, colors="black", linewidth=2.0)
ax.label(cp, inline=1, fontsize=10)
Julia
# Reference: https://groups.google.com/d/msg/julia-users/eVtZdp3htTM/TJOt3exCxKgJ
using Pkg
pkg"add Distributions"
using PyPlot
using Distributions
using LinearAlgebra
using3D() # Needed to create a 3D subplot
###################
##  Create Data  ##
###################
n = 100
x = range(-3,stop=3,length=n)
y = range(-3,stop=3,length=n)
xgrid = repeat(x',n,1)
ygrid = repeat(y,1,n)
z = zeros(n,n)
for i in 1:n, j in 1:n
    z[i:i,j:j] .= pdf(MvNormal(Matrix(1.0I,2,2)),[x[i];y[j]])
end
############
##  Plot  ##
############
fig = figure("pyplot_surfaceplot",figsize=(10,10))
ax = fig.add_subplot(2,1,1,projection="3d")
plot_surface(xgrid, ygrid, z, rstride=2,edgecolors="k", cstride=2, cmap=ColorMap("gray"), alpha=0.8, linewidth=0.25)
xlabel("X")
ylabel("Y")
title("Surface Plot")
subplot(212)
ax = fig.add_subplot(2,1,2)
cp = contour(xgrid, ygrid, z, colors="black", linewidth=2.0)
ax.clabel(cp, inline=1, fontsize=10)
xlabel("X")
ylabel("Y")
title("Contour Plot")
tight_layout()
gcf() # Needed for IJulia to plot inline
8.3s

Surface plot (3D)

surf(x,y,z,facecolors=colors)
Julia
using PyPlot
####################
##  Prepare Data  ##
####################
u = range(0.0, 2pi, length=300)
v = range(0.0, pi, length=300)
lu = length(u)
lv = length(v)
x = zeros(lu, lv)
y = zero(x)
z = zero(x)
for uu=1:lu, vv=1:lv
		x[uu,vv]= cos(u[uu])*sin(v[vv])
		y[uu,vv]= sin(u[uu])*sin(v[vv])
		z[uu,vv]= cos(v[vv])
end
#######################
##  Generate Colors  ##
#######################
colors = rand(lu,lv,3)
############
##  Plot  ##
############
figure()
surf(x,y,z,facecolors=colors)
gcf()
2.7s

Windrose bar and line plots

ax = axes(polar="true") # Create a polar axis
# Do your plotting
# Optional changes
ax.set_thetagrids(collect(0:dtheta:360-dtheta)) # Show grid lines from 0 to 360 in increments of dtheta
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot
ax.set_theta_direction(-1) # Switch to clockwise
fig.canvas.draw() # Update the figure
Julia
# pyplot_windrose.jl
#
#	Demonstrate windrose bar and line plots
#
# gizmaa (https://gist.github.com/gizmaa/7214002)
# Julia 1.1.0
# Last Edit: 10.05.19
using PyPlot
#################
#  Create Data  #
#################
theta = collect(0:2pi/30:2pi)
r = rand(length(theta))
width = 2pi/length(theta) # Desired width of each bar in the bar plot
##########################
##  Windrose Line Plot  ##
##########################
fig = figure("pyplot_windrose_lineplot",figsize=(10,10)) # Create a new figure
ax = PyPlot.axes(polar="true") # Create a polar axis
PyPlot.title("Wind Rose - Line")
p = plot(theta,r,linestyle="-",marker="None") # Basic line plot
dtheta = 10
ax.set_thetagrids(collect(0:dtheta:360-dtheta)) # Show grid lines from 0 to 360 in increments of dtheta
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot
ax.set_theta_direction(-1) # Switch to clockwise
fig.canvas.draw() # Update the figure
gcf() # Needed for IJulia to plot inline
1.7s
#########################
##  Windrose Bar Plot  ##
#########################
fig = figure("pyplot_windrose_barplot",figsize=(10,10)) # Create a new figure
ax = PyPlot.axes(polar="true") # Create a polar axis
PyPlot.title("Wind Rose - Bar")
b = bar(theta,r,width=width) # Bar plot
dtheta = 10
ax.set_thetagrids(collect(0:dtheta:360-dtheta)) # Show grid lines from 0 to 360 in increments of dtheta
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot
ax.set_theta_direction(-1) # Switch to clockwise
fig.canvas.draw() # Update the figure
gcf() # Needed for IJulia to plot inline
3.0s

XKCD style plots

Note: The IJulia example does not properly apply all the formatting as the terminal version does.

xkcd() # Set to XKCD mode, based on the comic (hand drawn)
# Plot everything
Julia
using PyPlot
# http://matplotlib.org/examples/showcase/xkcd.html
#################
#  Create Data  #
#################
x = 1:100
y = ones(length(x))
for i in 70:100
	y[i] = y[i] - (0.7/30)*(i-70)
end
##############
#  XKCD Plot #
##############
# backup rcParams
rc = PyPlot.matplotlib.rcParams
xkcd() # Set to XKCD mode, based on the comic (hand drawn)
fig = figure("pyplot_inexact",figsize=(10,10))
ax = PyPlot.axes()
p = plot(x,y)
ax.set_ylim([0.2;1.1])
annotate("THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED",xy=[70;1],arrowprops=Dict("arrowstyle"=>"->"),xytext=[25;0.8])
xticks([])
yticks([])
xlabel("TIME")
ylabel("MY OVERALL HEALTH")
PyPlot.title("Stove Owndership\nhttp://xkcd.com/418/")
ax.spines["top"].set_color("none") # Remove the top axis boundary
ax.spines["right"].set_color("none") # Remove the right axis boundary
fig.canvas.draw() # Update the figure
gcf()
1.4s
# Revert to original style
rcParams = PyPlot.PyDict(PyPlot.matplotlib."rcParams")
rcParams = rc
1.1s
Dict{Any,Any} with 299 entries: "animation.html_args" => Any[] "mathtext.bf" => "sans:bold" "legend.borderpad" => 0.4 "boxplot.medianprops.linestyle" => "-" "text.hinting_factor" => 8 "backend" => "agg" "savefig.pad_inches" => 0.1 "hatch.color" => "black" "xtick.minor.visible" => false "xtick.minor.width" => 0.6 "ytick.direction" => "out" "boxplot.capprops.linewidth" => 1.0 "legend.scatterpoints" => 1 "font.family" => ["sans-serif"] "polaraxes.grid" => true "figure.titleweight" => "normal" "animation.avconv_args" => Any[] "axes.autolimit_mode" => "data" "axes.facecolor" => "white" ⋮ => ⋮
Runtimes (1)