I working on a PyQt GUI in order to plot 2D/3D data.
Matplotlib is very interesting concerning all its available features.
However, Matplotlib seems to not be relevant when you have huge amount of data (for instance 10000x10000). I found that maybe GTKAgg backend is really efficient for this issue, but not really.
Maybe you can help me in order to enhance the performance of matplotlib when you want to pan or zoom in the figure.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.use('GTK3Agg')
fig, ax = plt.subplots()
n = 10000
Z = np.random.randint(10,size=(n,n))
ax.imshow(Z)
plt.show()
Related
using Python I would like to plot a curve for the function y=cosh(x)*cos(5x) in my Jupyter Notebook.
In other words:
(cosine hyperbolicus of x) times (cosine of 5x)
How do I do this?
What do I need to import?
Thank you very much in advance.
Greetings
Specify the range of values for x that you need.
You can use Seaborn on top of Matplotlib to make it prettier, but this is optional:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5,5,0.1) # start,stop,step
y= (np.cosh(x))*(np.cos(5*x) )
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above)
sns.set(style="darkgrid")
plt.plot(x,y)
plt.show()
You will need to import a plotting library and a maths library. The most commonly used plotting library is matplotlib, and for maths it's numpy. For plotting, bokeh is a an alternative to matplotlib, which I think is great because graphs are interactive by default. The disadvantage is that because it's not as widely used as matplotlib, you're less likely to find help on it in terms of StackOverflow answers and tutorials.
Anyway, to the code:
# Import the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np
# Set your x-range and calculate y
xmin = -2.5
xmax = 2.5
numPoints = 100
x = np.linspace(xmin, xmax, numPoints)
y = np.cosh(x)*np.cos(5*x)
# Plot -- it really can be this simple [1]
plt.plot(x,y)
Both of the graphing libraries above give you flexible options on where to place the axes, legends, titles, and so on. I recommend searching for beginner's tutorials on them to learn this stuff in depth.
[1] There are two ways to plot in matplotlib. What is shown here is the MATLAB-like interface. The other method is to use the object-based interface, which takes a bit more of getting used to, and requires a bit more boilerplate code, but that's what you will end up using once you demand more control over the appearance of your plots.
I recommend starting with the MATLAB-like commands first. The documentation has a good beginner's tutorial: https://matplotlib.org/stable/tutorials/introductory/pyplot.html
I would like to make a letter value plot using seaborn from a dataset that is too large to load into memory. Normally, I would do this:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_pickle('results_filename')
sns.lvplot(data=df, x='independent_variable', y='dependent_variable', hue='categorical_variable')
plt.show() # or savefig(...)
But my PC starts thrashing when results_filename is more than a few GB in size.
I can calculate the KDEs or histograms and save those to disk instead of the observations themselves.
I do that often when plotting stuff with pure matplotlib.
But is it possible to use sns.lvplot (or something similar) without passing the observations themselves to it?
When converting a matplotlib plot into a bokeh html plot, I see that the legend in the matplotlib plot does not appear in the bokeh html plot. Below is an example. How can I get the legend to show up in bokeh? Thanks.
import matplotlib.pyplot as plt
from bokeh.plotting import figure, show, output_file, save
from bokeh.mpl import to_bokeh
if __name__ == '__main__':
legend = ['x^2', '2x']
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(range(10), [x*x for x in range(10)], '-o')
plt.plot(range(10), [2*x for x in range(10)], '-o')
plt.legend(legend, loc='upper left')
plt.show()
bk = to_bokeh(fig)
show(bk
)
UPDATE: Please note Bokeh's current MPL compat has been deprecated and will be removed completely for Bokeh 1.0 release.
If MEP25 is ever implementented, it's possible MPL combat could return as a separate, add-on package.
Bokeh's MPL compat capability is based on an experimental third-party library that is no longer actively maintained. The to_bokeh functionality is provided as-is, and with the explicit expectation that it currently provides only partial coverage. More comprehensive compatibility will depend on the implementation of Matplotlib Enhancement Proposal 25 which would provide a stable and robust JSON serialization protocol for libraries like Bokeh to be able to interoperate with it. No work will be done on Bokeh's MPL compat until or if MEP25 is implemented. However, there has been no significant movement on MEP 25 in two years, so my strong recommendation, if you are looking to take advantage of Bokeh's features, is to use native Bokeh APIs such as bokeh.plotting directly, and to not rely on to_bokeh for anything serious.
I've been messing around with Mayavi for 3D graphing, and I can graph the scatter plot I want but can't seem to get the Axes to look proper. I found the following previous question that starts to get at what I'm after, but doesn't go into detail. I want a 3D scatter plot like #1 but with nice-looking axes like #2 (I'd embed but I don't have enough reputation).
The regular Mayavi Axes aren't going to cut it. Any tips for getting the planes that Matplotlib has?
This is actually pretty straightforward once we get the "trick", and I have done it many times.
The 'trick' is to generate the mayavi plot first, then transfer it into the matplotlib window where you can use all the familiar matplotlib tools to make axes with numbers, dates, arrows, or the other pieces that matplotlib provides. In this code example I'll just drop the mayavi 'copper spheres' example into a matplotlib set of axes:
import numpy, pylab, mayavi, mayavi.mlab
import matplotlib.pyplot as plt
t = numpy.linspace(0, 4 * numpy.pi, 20)
cos,sin = numpy.cos, numpy.sin
x = sin(2 * t)
y = cos(t)
z = cos(2 * t)
s = 2 + sin(t)
mayavi.mlab.points3d(x, y, z, s, colormap="copper", scale_factor=.25)
arr = mayavi.mlab.screenshot()
fig = plt.figure(figsize=(5, 5))
pylab.imshow(arr)
plt.show()
The result is just the mayavi plot in a matplotlib set of axes:
The only tricky part is that you'll need to build a working knowledge of the scales and dimensions of mayavi and matplotlib to get the two to scale together if you want to produce more than one or two manually built plots. That is non-trivial but fairly well documented for both Mayavi and Matplotlib and from the sounds of things you know both so I won't belabor those points. (Now that things are in Matplotlib you can make them part of generated PDFs too or port them into Microsoft Word with python-docx)
I have data (a spectrum) that I want to plot as a histogram.
I import the data and spectrum.shape shows me (1024,) as the format,
however plt.hist does not plot the data correctly.
If I use plt.bar(...) it works just fine, but for aesthetic reasons (I want to use the "stepfilled" histogram design) and I have to employ plt.hist which offers this option.
I really don't know what to do.
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
spectrum = np.loadtxt('3000.mp', skiprows=53)
y1=spectrum[:]
num_bins = 1024
diagram = plt.hist(y1, num_bins, alpha=0.5)
plt.xlabel("TOF / $\mu$s")
plt.ylabel("# ions")
plt.show()
I hope for your help.
I am interested also in this answer. Would you share how did you get the stepfilled design with bars?
Myself I am looking for something like this:
(this image comes from http://astroplotlib.stsci.edu/page_histograms.htm)
But I do not manage to generate it easily with a spectrum as an input.