I have this code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
a = np.array([1,2,3])
b = a
ax1.plot(a,b)
ax2 = ax1.twinx()
ax2.set_position(matplotlib.transforms.Bbox([[0.125, 0.125], [0.9, 0.2]]))
c = np.array([4,5,6])
d = c
ax2.plot(c,d)
plt.show()
When I run this with Python 2, it results in:
The problem is when I try to use the same code using Python 3 I get this picture:
How can I have the same result using Python 3?
This was a bug, which has now been fixed (so it has nothing to do with the python version, but rather the matplotlib version in use). You could use an inset_axes instead of just a usual subplot. The latter could look like this:
import numpy as np
from matplotlib.transforms import Bbox
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111, label="first")
ax2 = fig.add_subplot(111, label="second")
ax2.set_position(Bbox([[0.125, 0.125], [0.9, 0.2]]))
ax1.get_shared_x_axes().join(ax1, ax2)
ax2.yaxis.tick_right()
ax2.tick_params(bottom=False, labelbottom=False)
ax2.set_facecolor("none")
a = np.array([1,2,3])
ax1.plot(a,a)
c = np.array([4,5,6])
ax2.plot(c,c)
plt.show()
Related
The following code generates a simple plot, where the y axes has a label generated by a LaTeX command
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
plt.figure()
hatdelta = '$\hat{\Delta}$'
xlist = np.array([ 0, 1 ])
ylist = np.array([ 1, 2 ])
plt.errorbar(xlist, ylist, fmt='o', capsize=2)
ax = plt.gca()
ax.set_ylabel(hatdelta, fontsize=16)
plt.draw()
plt.show()
I am using jupyter-notebook to run the code.
This is the actual result:
A close inspection of the y axes reveals that the LaTeX is incorrectly rendered:
The hat is not centered over the symbol. However, the LaTeX code should correctly center the hat. This is, for example, the output of a LaTeX source with the same command:
Is it possible to fix this incorrect LaTeX rendering?
You have two options.
import numpy as np
import matplotlib.pyplot as plt
# To use LaTeX
plt.rcParams['text.usetex'] = True
plt.figure()
hatdelta = '$\hat{\Delta}$'
xlist = np.array([ 0, 1 ])
ylist = np.array([ 1, 2 ])
plt.errorbar(xlist, ylist, fmt='o', capsize=2)
ax = plt.gca()
ax.set_ylabel(hatdelta, fontsize=16)
plt.draw()
plt.show()
Or
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
# Improve \hat
hatdelta = '$\hat{\,\Delta}$'
xlist = np.array([ 0, 1 ])
ylist = np.array([ 1, 2 ])
plt.errorbar(xlist, ylist, fmt='o', capsize=2)
ax = plt.gca()
ax.set_ylabel(hatdelta, fontsize=16)
plt.draw()
plt.show()
I am currently have a nx3 matrix array. I want plot the three columns as three axis's.
How can I do that?
I have googled and people suggested using Matlab, but I am really having a hard time with understanding it. I also need it be a scatter plot.
Can someone teach me?
You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.
import matplotlib.pyplot as plt
import random
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(projection='3d')
sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))
random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)
ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
plt.show()
The code above generates a figure like:
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
scatter plot
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata);
Colab notebook
Using plotly - Easiest and most functional and nice plots
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species')
fig.show()
https://plotly.com/python/3d-scatter-plots/
I'm trying to plot 23 graphs in a 6x4 grid, with one figure taking up twice the width of the other figures. I'm using gridspec and my current code is:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
x = np.arange(0, 7, 0.01)
fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=6, ncols=4)
for n in range(22):
ax = fig.add_subplot(gs[n])
ax.plot(x, np.sin(0.2*n*x))
corrax = fig.add_subplot(gs[22])
fig.tight_layout()
plt.show()
This produces the following:
I want to increase the width of the rightmost plot in the bottom row so it takes up the remaining space in that row. Is there a way to accomplish this?
You can use slices to select several positions from the gridspec, e.g. gs[22:24].
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
x = np.arange(0, 7, 0.01)
fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=6, ncols=4)
for n in range(22):
ax = fig.add_subplot(gs[n])
ax.plot(x, np.sin(0.2*n*x))
corrax = fig.add_subplot(gs[22:24])
corrax.plot(x,np.sin(0.2*22*x), color="crimson", lw=3)
fig.tight_layout()
plt.show()
You can also slice the gridspec two-dimensionally. E.g. to create a 3x3 grid and make the plot in the lower right corner span two columns and two rows, you could slice like gs[1:,1:].
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
x = np.arange(0, 7, 0.01)
fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=3, ncols=3)
for n in range(3):
ax = fig.add_subplot(gs[0,n])
ax.plot(x, np.sin(0.2*n*x))
if n !=0:
ax = fig.add_subplot(gs[n,0])
ax.plot(x, np.sin(0.2*n*x))
corrax = fig.add_subplot(gs[1:,1:])
corrax.plot(x,np.sin(0.2*22*x), color="crimson", lw=3)
fig.tight_layout()
plt.show()
#corrax = fig.add_subplot(gs[5,2:])
corrax = fig.add_subplot(6,4,(23,24))
both shold work.
see examples
I am new to Matplotlib, and as I am learning how to draw box plot in python, I was wondering if there is a way to show mean in the box plots?
Below is my code..
from pylab import *
import matplotlib.pyplot as plt
data1=np.random.rand(100,1)
data2=np.random.rand(100,1)
data_to_plot=[data1,data2]
#Create a figure instance
fig = plt.figure(1, figsize=(9, 6))
# Create an axes instance
axes = fig.add_subplot(111)
# Create the boxplot
bp = axes.boxplot(data_to_plot,**showmeans=True**)
Even though I have showmean flag on, it gives me the following error.
TypeError: boxplot() got an unexpected keyword argument 'showmeans'
This is a minimal example and produces the desired result:
import matplotlib.pyplot as plt
import numpy as np
data_to_plot = np.random.rand(100,5)
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(data_to_plot, showmeans=True)
plt.show()
EDIT:
If you want to achieve the same with matplotlib version 1.3.1 you'll have to plot the means manually. This is an example of how to do it:
import matplotlib.pyplot as plt
import numpy as np
data_to_plot = np.random.rand(100,5)
positions = np.arange(5) + 1
fig, ax = plt.subplots(1,2, figsize=(9,4))
# matplotlib > 1.4
bp = ax[0].boxplot(data_to_plot, positions=positions, showmeans=True)
ax[0].set_title("Using showmeans")
#matpltolib < 1.4
bp = ax[1].boxplot(data_to_plot, positions=positions)
means = [np.mean(data) for data in data_to_plot.T]
ax[1].plot(positions, means, 'rs')
ax[1].set_title("Plotting means manually")
plt.show()
Result:
You could also upgrade the matplotlib:
pip2 install matplotlib --upgrade
and then
bp = axes.boxplot(data_to_plot,showmeans=True)
I am trying to plot a colorbar in Python using the matplotlib libraries. The plot works well, but the color bar wont show the end ticks on the color bar.
Using the following command plots the colorbar properly, but I only have ticks ranging from -1.6 to +1.6 ( the top and bottom ticks are absent). The range of my data is from -2 to +2.
fig.colorbar(surf, shrink=1, aspect=12)
This is seen in the following figure:
I tried using the command:
cbar.set_ticks([-2,-1,0,1,2]);
But that also failed to get the correct result.
UPDATE:
I tried using the ticks=[-2,0,2] parameter, but that did not work as well. This is a snippet of my plotting code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35)
CHI, M = np.meshgrid(CHI, M)
R = 2*M*np.sin( 2 * np.deg2rad(CHI) )
surf = ax.plot_surface(CHI, M, R, rstride=1, cstride=1, cmap=cm.hsv,linewidth=0, antialiased=False)
ax.set_xlim(-45,45)
cbar = plt.colorbar(surf, shrink=1, aspect=12, ticks=[-2,-1,0,1,2])
plt.show()
This produces the following plot:
As seen, the colorbar lacks the end ticks, viz. -2 and 2
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35)
CHI, M = np.meshgrid(CHI, M)
R = 2*M*np.sin( 2 * np.deg2rad(CHI) )
surf = ax.plot_surface(CHI, M, R, rstride=1, cstride=1, cmap=cm.hsv,linewidth=0, antialiased=False)
surf.set_clim([-2, 2]) # <- this is the important line
ax.set_xlim(-45,45)
cbar = plt.colorbar(surf, shrink=1, aspect=12, ticks=[-2,-1,0,1,2])
plt.show()
Something is going wrong with the auto-scaling (I would guess issues with floating point equality tests), if you explicitly set the clim to [-2, 2] it works.
You should be able to set the ticks parameter when calling plt.colorbar:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
cmap = plt.get_cmap('jet')
data = np.random.randint(-2,3, size=(10,10))
im = ax.imshow(data, interpolation='nearest', cmap=cmap)
cbar = plt.colorbar(im, ticks=[-2,-1,0,1,2])
plt.show()