Adding a custom scale to an imported image in python - python-2.7

I am attempting to add a scale to an imported image. I have gotten as far as to defining the extent of the image (what I want the scale to represent). When I run the code below, the x axis has ticks that go from 0,20,-20,-40,40. I would like the ticks to represent the full extent of the x-axis. Do i need to import another library separately in order to achieve this?
from PIL import Image
import matplotlib.pyplot as plt
img= Image.open("image.png")
plt.imshow(img, extent=(-55.0,55.0,0,5));
axes = plt.gca()
axes.set_xlim([-55.0,55.0])
axes.get_yaxis().set_visible(False)
plt.xlabel('Vs - Vs_mean (m/s)', size=8)
Also, I am still relatively new to python and am still attempting to figure out libraries. I have read into matplotlib.ticker which may be a sloution, but I'm not exactly sure how the matplotlib.ticker and matplotlib.pyplot interact. Do i need to save the image as something different after defining the extent before moving on to matplotlib.ticker?
Thanks for your time, it is greatly appreciated.

Related

Creating a colorbar next to my matplotlib plot w/o using the colormap to plot the data

I'm having trouble creating a colorbar for my plot in Python using matplotlib. I am using a colormap, not to colour all the data that I plot but to extract a colour for a plot based on a value I'm not plotting. Hope this makes sense..
So I'm in a for loop, create a plot every time with a colour based on a certain parameter. Like this (the data is an example to create an mwe, my data is more complicated):
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
xdata = np.array(range(10))
parameter = [0.5, 0.3, 0.78, 0.21, 0.45] #random parameter example
cmap = mpl.cm.get_cmap('jet')
for i in range(len(parameter)):
clr = cmap(parameter(i))
plt.plot(xdata,xdata**i,c=clr)
plt.show()
Now, what I would want is a colorbar on the side (or actually two, but that's another problem I think) that shows the jet colormap and according values. The values need to be scaled to a new min and max value.
So far I've found the following, but I don't understand it enough to apply it to my own problem:
Getting individual colors from a color map in matplotlib
Which told me how to extract the colour and shows how to create the normalized colormap
Colorbar only
Which should tell me how to add a colorbar without using the plotted data, but I don't understand enough of it. My problem is with the creation of the axes. I don't understand this part if I want to put the colorbar next to my plot. In the example they create a figure with handle fig, but in my case the figure is created when I do plt.imshow(image), since this is what I start with and then I'm plotting over the image. I cannot use the fig.add_axes here.
I hope you can help me out here. It would be great if I could also create a 'reversed' colorbar. So either the colours are in reverse direction, or the values next to the bar.
At any point in the script you can get the figure via fig = plt.gcf() and an axes via ax=plt.gca(). So, adding an axes may be done by plt.gcf().add_axes(...).
There is also nothing wrong with putting fig=plt.figure() before plotting anything.
Note that after creating a new axes, plt.gca() will return the new axes, so it is a good idea to create a reference to the main axes before adding a new one.
A convenient way to obtain a figure and an axes for later referencing is to create the figure via
fig, ax = plt.subplots()
Colormaps:
Every standard colormap has a reversed version, which has _r at the end of its name, e.g. you can use viridis_r instead of viridis.

Matplotlib funcAnimation does not open/show plot

I'm trying to learn how to animate plots using matplotlib's built in funcAnimation class. For this example, I just want to generate a 2D scatter plot of randomly distributed normal values and add a point to the plot (animate the points appearing) each time I update the points. The example code is below:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
plt.ion()
fig, ax = plt.subplots()
scat = ax.scatter([],[])
scat.axes.axis([-5, 5, -5, 5])
def update(point):
array = scat.get_offsets()
array = np.append(array, point)
scat.set_offsets(array)
return scat
def data_gen():
for _ in range(0,100):
point = np.random.normal(0, 1, 2)
yield point
ani = animation.FuncAnimation(fig, update, data_gen, interval=25, blit=False)
plt.show()
When I run this code, nothing happens. The terminal churns for a few seconds, and then nothing happens.
I'm using this as my guide: http://matplotlib.org/examples/animation/animate_decay.html, and if I use a line plot instead of a scatter plot (essentially just replacing how the points are generated in the generator of this example) it "works" as far as it generates data and updates the plots. But it is not the display I want, I want to see the point appearing on a scatter plot. To use a scatter plot, I need to not use set_data, as that is not a valid method for scatter plots; so I'm using the np.append() method which I've seen in this example:
Dynamically updating plot in matplotlib
So my question is, what am I doing wrong in this code that is causing the animation to not show up?
EDIT: I've just tried/found out that if I add:
mywriter = animation.FFMpegWriter(fps=60)
ani.save('myanimation.mp4',writer=mywriter)
It does produce an mp4 that contains the animation, I just can't get it to dynamically display as the code is running. So please focus on that problem if you are able to diagnose it. Thanks.
For future reference, #ImportanceOfBeingErnest pointed out that plot.ion() is not necessary and is specific to plotting in ipython. Removing that fixes the problem.

Figure Size & Position after Matplotlib Zoom

I have a matplotlib image plot within a wxPython panel that I zoom in on using the native matplotlib toolbar zoom.
Having zoomed in I wish to know the size of the resulting image so that I can calculate the magnification.
Moreover, I wish to know the position/dimensions of my zoomed in image in relation to the original image so that I can re-plot it again at a later time.
I don't know how to approach this. I have looked over documentation for canvas and figure but haven't found anything which would help me pin point the data I require. Thanks for any help.
You may want to read the following from the matplotlib doc:
Event handling and picking
Transformations tutorial
However, especially the transformations tutorial may take a while to wrap your head around. The transformation system is very efficient and complete, but it may take you a while to figure out what especially it is you do need.
However in your case maybe the following code snippet could be sufficient:
from matplotlib import pyplot as plt
import numpy
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(numpy.random.rand(10))
def ondraw(event):
# print 'ondraw', event
# these ax.limits can be stored and reused as-is for set_xlim/set_ylim later
print ax.get_xlim(), ax.get_ylim()
cid = fig.canvas.mpl_connect('draw_event', ondraw)
plt.show()
In the draw event you can get your axes limits, calculate a scaling and whatnot and can use it as-is later on to set the ax to the desired zoom level.

Saving the matplotlib 3d rotating plots

Hi does anyone know if there is a way of saving the matplotlib 3d rotating plots in a format which allows them to be still rotated? Perhaps a particular program?
Code is:
from numpy import *
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
A=transpose(genfromtxt("Z:/Desktop/Project/bhmqntm-code/RichardsonRK4.csv", unpack=True, delimiter=','))
T=A[:,0]
X=A[:,1]
P=A[:,2]
fig=p.figure()
ax = p3.Axes3D(fig)
ax.scatter(X,P,T,s=1,cmap=cm.jet)
ax.set_xlabel('X')
ax.set_ylabel('P')
ax.set_zlabel('T')
p.show()#I would like this to be something like savefig('Z:/Desktop/Project/bhmqntm-code/plot3d_ex.png') but with a file ending of a program that would save the 3d capability
I'm not sure if a program which does this actually exists but if anyone knows of one it would be very helpful. Thanks.
I do not think matplotlib can do it.
The solution I found is to make graphs to display them in the browser. For example use plot.ly.
An example: https://plot.ly/python/ipython-notebook-tutorial/#3d-plotting

yticklabels on the opposite axis

I'm trying to plot the yticklabels of a figure made with imshow on the opposite axis. Also I need to set the ticklabels so what I need to control over this axis. Does anyone know how to do this?
Thanks in advance.
Try this:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
plt.imshow(...)
ax.yaxis.set_tick_params(labelright=True, labelleft=False)