How can I make that when I plot a function (based on a np.array) certain values have their coordinates in the plot?
I know how to change color and other little things with code lines like:
line1, = plt.plot(t, f, '*-', label='force', color='#4F81BD') # blue
line2, = plt.plot(t, a, 'o-', label='acceleration', color='#C0504D') # red
but for example if I have a "peak" in the plot line, I don't know how to make their coordinates to appear in the same plot
This code snippet might help you:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x=[1,2,3,4,5,6,7,8,9,10]
y=[1,1,1,2,10,2,1,1,1,1]
line, = ax.plot(x, y)
ymax = max(y)
xpos = y.index(ymax)
xmax = x[xpos]
#Labeling the graph (ymax+1 is defining the distance from the word to the point)
ax.annotate('local max', xy=(xmax, ymax), xytext=(xmax, ymax+1))
ax.set_ylim(0,20)
plt.show()
Output:
I hope I could help you out a bit.
Related
I'm learning Python using Jupiter and I'm struggling trying to put the graphs into one figure. Here's what I have so far...
Code for my graphs(I have three of graphs, they only differ in color and lines vs. dot):
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
one = plt.figure()
plt.plot(x_v, y_v, '#008000') #change color using hex strings
plt.xlabel('x')
plt.ylabel('y')
plt.show()
two = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
plt.show()
three = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
plt.show()
Here's code that I have so far to make it one figure... I was wondering If I should should put it in a np.arange and plot it, but I can't seem to get it to work....
def f(x):
return one
def g(x):
return two
def h(x):
return three
If anyone can help, it'll be of great use! Thank you!
You can use plt.subplots:
fig, (ax1, ax2, ax3) = plt.subplots(figsize=(15, 5), ncols=3)
ax1.plot(x_v, y_v, '#008000')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax2.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
ax3.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
Here is one way to approach multiple plots with plt.subplots. I think it is very easy to follow and also gives a lot of control over individual plots:
import numpy as np
import matplotlib.pyplot as plt
#generating test data
x = np.arange(0,9)
y = np.arange(1,10)
#defining figure layout (i.e. rows, columns, size, horizontal and vertical space between subplots
fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(15,7))
plt.subplots_adjust(hspace=0.4,wspace=0.2)
#first subplot (numbering can be read as 1st plot in a grid of 2x2)
plt.subplot(2,2,1)
plt.plot(x,y)
#second subplot in a grid of 2x2
plt.subplot(2,2,2)
plt.plot(x,y,ls='--')
#third subplot in a grid of 2x2
plt.subplot(2,2,3)
plt.scatter(x,y)
#fourth subplot in a grid of 2x2
plt.subplot(2,2,4)
plt.plot(x,y)
plt.tight_layout()
plt.show()
Output:
I'm trying to plot a polar plot with this code:
import numpy as np
import matplotlib.pylab as plt
def power(angle, l, lam):
return 1/(lam) * ((np.cos(np.pi*l*np.cos(angle)/lam) - np.cos(np.pi*l/lam))/np.sin(angle))**2
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='polar')
theta = np.linspace(0.001, 2*np.pi, 100)
P1 = power(theta, 1, 5)
ax.plot(theta, P1, color='r', linewidth=3)
plt.savefig('1.png')
and I get this plot:
I would like to change 2 things. The first and more important one is to hide the radial tick labels (I just want to show the general form of the plot).
If possible, how can I choose the vertical axis to correspond to 0°?
Thanks for your help.
You can use set_yticklabels() to remove the radial ticks and set_theta_zero_location() to change the zero location:
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='polar')
ax.plot(theta, P1, color='r', linewidth=3)
ax.set_yticklabels([])
ax.set_theta_zero_location('N')
plt.show()
You might also want to change the direction of the azimuthal axis:
ax.set_theta_direction(-1)
You can set the theta zero position with ax.set_theta_zero_location('N').
To modify the r tick labels, you could do something like
for r_label in ax.get_yticklabels():
r_label.set_text('')
If you want to remove them entirely, do ax.set_yticklabels([]).
More methods can be found in the PolarAxes documentation.
I have two lists containing the x and y coordinates of some points. There is also a list with some values assigned to each of those points. Now my question is, I can always plot the points (x,y) using markers in python. Also I can select colour of the marker manually (as in this code).
import matplotlib.pyplot as plt
x=[0,0,1,1,2,2,3,3]
y=[-1,3,2,-2,0,2,3,1]
colour=['blue','green','red','orange','cyan','black','pink','magenta']
values=[2,6,10,8,0,9,3,6]
for i in range(len(x)):
plt.plot(x[i], y[i], linestyle='none', color=colour[i], marker='o')
plt.axis([-1,4,-3,4])
plt.show()
But is it possible to choose a colour for the marker marking a particular point according to the value assigned to that point (using cm.jet, cm.gray or similar other color schemes) and provide a colorbar with the plot ?
For example, this is the kind of plot I am looking for
where the red dots denote high temperature points and the blue dots denote low temperature ones and others are for temperatures in between.
You are most likely looking for matplotlib.pyplot.scatter. Example:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Generate data:
N = 10
x = np.linspace(0, 1, N)
y = np.linspace(0, 1, N)
x, y = np.meshgrid(x, y)
colors = np.random.rand(N, N) # colors for each x,y
# Plot
circle_size = 200
cmap = matplotlib.cm.viridis # replace with your favourite colormap
fig, ax = plt.subplots(figsize=(4, 4))
s = ax.scatter(x, y, s=circle_size, c=colors, cmap=cmap)
# Prettify
ax.axis("tight")
fig.colorbar(s)
plt.show()
Note: viridis may fail on older version of matplotlib.
Resulting image:
Edit
scatter does not require your input data to be 2-D, here are 4 alternatives that generate the same image:
import matplotlib
import matplotlib.pyplot as plt
x = [0,0,1,1,2,2,3,3]
y = [-1,3,2,-2,0,2,3,1]
values = [2,6,10,8,0,9,3,6]
# Let the colormap extend between:
vmin = min(values)
vmax = max(values)
cmap = matplotlib.cm.viridis
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
fig, ax = plt.subplots(4, sharex=True, sharey=True)
# Alternative 1: using plot:
for i in range(len(x)):
color = cmap(norm(values[i]))
ax[0].plot(x[i], y[i], linestyle='none', color=color, marker='o')
# Alternative 2: using scatter without specifying norm
ax[1].scatter(x, y, c=values, cmap=cmap)
# Alternative 3: using scatter with normalized values:
ax[2].scatter(x, y, c=cmap(norm(values)))
# Alternative 4: using scatter with vmin, vmax and cmap keyword-arguments
ax[3].scatter(x, y, c=values, vmin=vmin, vmax=vmax, cmap=cmap)
plt.show()
Currently I have the following script that generates a polar plot of azimuth/radius data. "R1" is simple a list of values of [azimuth, inclination] derived from a table in ArcGIS.
import matplotlib.pyplot as plt
import numpy as np
for(a,r) in R1:
angles.append(a)
radius.append(90-r)
theta = np.radians(angles)
r = radius
ax = plt.subplot(111,polar=True)
ax.plot(theta, r, color='black', ls='-', linewidth=1)
ax.fill(theta,r,'0.75') ## should I use ax.fill_betweenx() ?
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_rmax(90)
ax.set_rmin(0)
ax.set_yticks(range(0,90,10))
yLabel=['90','','','60','','','30','','','']
ax.set_yticklabels(yLabel)
ax.grid(True)
plt.show()
At the moment this creates the following plot:
How can I "invert" the fill so that what is filled with gray will be white, and what is white will be gray?
I have tried ax.fill_betweenx(theta,90,r,color='0.75') and that didn't work. I have been battling with this for some time now to no avail.
ANY help or suggestions are greatly appreciated!
If there is any way I can make this clearer, please let me know in the comments.
Depending on what you want to do with this later, the quickest way is to simply make the background gray and the fill white:
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111, polar=True)
theta = np.linspace(0, 2*np.pi, 100)
r = 2 + np.sin(theta * 2)
ax.patch.set_facecolor('0.5')
ax.plot(theta, r, color='black', ls='-', linewidth=1)
ax.fill(theta,r,'w')
plt.show()
plt.draw() # just to be safe!
I want to draw x=0 and y=0 axis in my contour plot, using a white color. If that is too cumbersome, I would like to have a white dot denoting where the origin is.
My contour plot looks as follows and the code to create it is given below.
xvec = linspace(-5.,5.,100)
X,Y = meshgrid(xvec, xvec)
fig = plt.figure(figsize=(6, 4))
contourf(X, Y, W,100)
plt.colorbar()
There are a number of options (E.g. centered spines), but in your case, it's probably simplest to just use axhline and axvline.
E.g.
import numpy as np
import matplotlib.pyplot as plt
xvec = np.linspace(-5.,5.,100)
x,y = np.meshgrid(xvec, xvec)
z = -np.hypot(x, y)
plt.contourf(x, y, z, 100)
plt.colorbar()
plt.axhline(0, color='white')
plt.axvline(0, color='white')
plt.show()
Can't you just overlay a straight line?
plt.plot([0,0],[-4,4],lw=3,'w')