python, matplotlib.pyplot, draw graph without the curve - python

I am trying to draw a curve without a line (skeleton). I want the axis and grid lines only.
Here is the code.
++++++++++
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10.00, 7.00]
plt.rcParams["figure.autolayout"] = True
x = [1.6,2,2.5,3.2,4,5,6.3,8,10,13,16,20,25,32,40,50,63,80,100,130,160,200,250,320,400,500,630,800,1000]
y = range(1,10000,350)#[1,10,100,1000,10000]
# Display grid
plt.grid(True, which="both")
default_x_ticks = range(len(x))
plt.plot(default_x_ticks, y)
plt.yscale('log')
plt.xticks(default_x_ticks, x, rotation=90)
plt.show()
+++++++
Kindly help draw without the curve.

By adding
print(plt.xlim())
print(plt.ylim())
to your code you get the exact axis limits.
These can be used in a second run to create the plot without actually plotting anything:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10.00, 7.00]
plt.rcParams["figure.autolayout"] = True
x = [1.6,2,2.5,3.2,4,5,6.3,8,10,13,16,20,25,32,40,50,63,80,100,130,160,200,250,320,400,500,630,800,1000]
y = range(1,10000,350)#[1,10,100,1000,10000]
# Display grid
plt.grid(True, which="both")
default_x_ticks = range(len(x))
# plt.plot(default_x_ticks, y)
plt.yscale('log')
plt.xticks(default_x_ticks, x, rotation=90)
plt.xlim(-1.4, 29.4)
plt.ylim(0.6315917965717447, 15517.934294269562)
plt.show()

Related

Scatter plot - how to do it

I would like to reproduce this plot in Python: (https://i.stack.imgur.com/6CRfn.png)
Any idea how to do this?
I tried to do a normal plt.scatter() but I can't draw this axes on the zero, for example.
That's a very general question... Using plt.scatter() is certainly a good option. Then just add the two lines to the plot (e.g. using axhline and axvline).
Slightly adapting this example:
import numpy as np
import matplotlib.pyplot as plt
# don't show right and top axis[![enter image description here][1]][1]
import matplotlib as mpl
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
# some random data
N = 50
x = np.random.randint(-10, high=11, size=N, dtype=int)
y = np.random.randint(-10, high=11, size=N, dtype=int)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2 # 0 to 15 point radii
# creating a vertical and a horizontal line
plt.axvline(x=0, color='grey', alpha=0.75, linestyle='-')
plt.axhline(y=0, color='grey', alpha=0.75, linestyle='-')
# scatter plot
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

matplotlab How can I plot points in a loop using one array

This is a simplified example of a problem I am having.
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1)
plt.show()
shows this. and
x = y = []
for i in range(0,10):
x.append(i)
y.append(i + 1)
plt.plot(x, y,)
plt.show()
shows this.
How can I plot points in a loop so that I don't need to create two arrays?
Try this-
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1, color='green', linestyle='solid', linewidth = 3,
marker='o')
plt.show()
Pass array as the first argumet to plt.plot(), this would plot y using x as index array 0..N-1:
import matplotlib.pyplot as plt
# plot y using x as index array 0..N-1
plt.plot(range(10))
plt.show()
You'll find more interesting information at plt.plot().
You can do it with:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
fig, ax = plt.subplots()
max =10
for i in range(0,max):
#scatter:
#s=0 to make dissapeared the scatters
ax.scatter(i, i + 1,s=1,facecolor='blue')
#lines
if i > 0:
lc = LineCollection([[(i-1, i),(i, i+1)]])
ax.add_collection(lc)
plt.show()
result:

removing outline color of scatter plot in matplotlib python

Suppose I have gridded data with dimensions (x,y) and values are in z.
so simply we can make scatter plot for third dimension by:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
plt.scatter(x, y, c = z, s=150, cmap = 'jet')
plt.show()
what i am thinking now is to remove the line color of each circular scatter plot. And also instead of circle can we make it square??
I did not find any way to do that. your help will be highly appreciated.
Pass the argument edgecolors='none' to plt.scatter. The patch boundary will not be drawn.
Pass the argument marker='s' to plt.scatter. The marker style will be square.
Then, we have,
The source code,
import numpy as np
import matplotlib.pyplot as plt
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
plt.scatter(x, y, c = z, s=150, cmap = 'jet', edgecolors='none', marker='s')
plt.show()
Refer to matplotlib.pyplot.scatter for more information.

python matplotlib gridspec, unwanted arbitrary axis labels

I have some code to plot a grid, with the data in each cell being distinct and having a very specific position. The easiest way I found to do this was to create the grid with gridspec and use it to precisely position my subplots, however I'm having a problem where the overall grid is labelled from 0 to 1 along each axis. This happens every time, even when the dimensions of the grid are changed. Obviously these numbers have no relevance to my data, and as what I am aiming to display is qualitative rather than quantitative I would like to remove all labels from this plot entirely.
Here is a link to an image with an example of my problem
And here is the MWE that I used to create that image:
import numpy as np
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
# mock-up of data being used
x = 6
y = 7
table = np.zeros((x, y))
# plotting
fig = plt.figure(1)
gs = gridspec.GridSpec(x, y, wspace=0, hspace=0)
plt.title('Example Plot')
for (j, k), img in np.ndenumerate(table):
ax = fig.add_subplot(gs[x - j - 1, k])
ax.set_xticklabels('')
ax.set_yticklabels('')
plt.show()
I have not been able to find note of anything like this problem, so any help would be greatly appreciated.
If you just want to draw a grid over the plot, use this code:
import numpy as np
import matplotlib.pyplot as plt
# mock-up of data being used
x = 6
y = 7
table = np.zeros((x, y))
# plotting
fig = plt.figure(1)
plt.title('Example Plot')
plt.gca().xaxis.grid(True, color='darkgrey', linestyle='-')
plt.gca().yaxis.grid(True, color='darkgrey', linestyle='-')
plt.show()
Another variant is used gridspec:
...
# hide ticks of main axes
ax0 = plt.gca()
ax0.get_xaxis().set_ticks([])
ax0.get_yaxis().set_ticks([])
gs = gridspec.GridSpec(x, y, wspace=0, hspace=0)
plt.title('Example Plot')
for (j, k), img in np.ndenumerate(table):
ax = fig.add_subplot(gs[x - j - 1, k])
# hide ticks of gribspec axes
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])

Plot NumPy ndarray into a 3D surface

I have a numpy.ndarray of size 200x200. I want to plot it as a 3D surface where x and y are indexes of the array and z is the value of that array element. Is there any easy way to do it or do I have to transform my array into a long list?
For example using matplotlib:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
#your index
x = np.linspace(1, 200, 200);
y = np.linspace(1, 200, 200)
X, Y = np.meshgrid(x, y); #making a grid from it
fig = plt.figure()
ax = fig.gca(projection='3d')
R = np.sqrt(X**2 + Y**2) #make some calculations on the grid
Z = np.sin(R) #some more calculations
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-5, 5)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
However, as your array is already quite large, you might want to consider a different plotting tool like mayavi. matplotlib usually puts a copy of your complete array into the plot. That's memory demanding when dealing with big data. But I'm not sure, whether mayavi does the same or not.
You can also use mayavi and plot your array as a plane with different colors representing the values. It would look like this:
import numpy
from mayavi import mlab
mlab.imshow(yourarray)
mlab.show()
Alternative you can create points with an elevation from the ground plane and get a fitting plane through the points. See here:http://docs.enthought.com/mayavi/mayavi/auto/example_surface_from_irregular_data.html#example-surface-from-irregular-data
What is best for you depends on the continuity of your data.
If what you want is to plot a 3D surface on top of a 2D grid what you could do is something similar to this:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# create some fake data
array_distribution3d = np.ones((200, 200))
array_distribution3d[0:25, 0:25] = -1
# create the meshgrid to plot on
x = np.arange(0, array_distribution3d.shape[0])
y = np.arange(0, array_distribution3d.shape[1])
# here are the x,y and respective z values
X, Y = np.meshgrid(x, y)
z = []
for i in range(0, array_distribution3d.shape[0]):
z_y = []
for j in range(0, array_distribution3d.shape[1]):
z_y.append(array_distribution3d[i, j])
z.append(z_y)
Z = np.array(z)
# create the figure, add a 3d axis, set the viewing angle
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection='3d')
ax.view_init(45, 60)
# here we create the surface plot
ax.plot_surface(X, Y, Z)
However, to the best of my knowledge, this kind of data can be plotted as a colourmap.
This can be plotted as follows:
import numpy as np
import os.path
import matplotlib.pyplot as plt
array_distribution = np.ones((200, 200))
array_distribution[0:25, 0:25] = -1
fig = plt.imshow(array_distribution)
plt.colorbar(fraction=0.035, pad=0.035, ticks=[-1., 0., 1.])
axes = plt.gca()
axes.set_ylim([0, 200])
figure = plt.gcf()
file = os.path.join('demo1.png')
figure.savefig(file, dpi=250)
plt.close('all')
print('done')

Categories