This question already has an answer here:
Matplotlib: automatically modify axis labels
(1 answer)
Closed 3 years ago.
I have following code:
import matplotlib.pyplot as plt
x = [i * 2872155 for i in range(1, 11)]
y = [0.219, 0.402, 0.543, 0.646,0.765, 0.880,1.169, 1.358,1.492,1.611]
plt.plot(x, y)
and the plot is
But I want the y label to be like 0.2s, 0.4s, 0.6s.
How can I do this?
Try this:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
x = [i * 2872155 for i in range(1, 11)]
y = [0.219, 0.402, 0.543, 0.646,0.765, 0.880,1.169, 1.358,1.492,1.611]
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.1f s'))
plt.plot(x, y)
plt.show()
Or use:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [i * 2872155 for i in range(1, 11)]
y = [0.219, 0.402, 0.543, 0.646,0.765, 0.880,1.169, 1.358,1.492,1.611]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1fs'))
plt.show()
you can use type conversion if you just want to add 's' to y values
x = [i * 2872155 for i in range(1, 11)]
y = [0.219, 0.402, 0.543, 0.646,0.765, 0.880,1.169, 1.358,1.492,1.611]
z = [str(i)+'s' for i in y]
plt.plot(x, z)
plt.show()
Related
This question already has answers here:
How to plot multiple functions on the same figure, in Matplotlib?
(4 answers)
Closed 1 year ago.
How to build two graphs in one figure from the equations below
y = (x+2)^2
y = sin(x/2)^2
There is my code:
import matplotlib.pyplot as plt
import numpy as np
from math import sin
y = lambda x: sin(x / 2) ** 2
y1 = lambda x: (x + 2) ** 2
fig = plt.subplots()
x = np.linspace(-3, 3, 100)
plt.plot(x, y(x))
plt.plot(x, y1(x))
plt.show()
Use supplots to make 2 Axes in your Figure:
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1,ax2) = plt.subplots(nrows=2)
x = np.linspace(-3, 3, 100)
ax1.plot(x, np.sin(x / 2) ** 2)
ax2.plot(x, (x + 2) ** 2)
I can use the set_xdata and set_ydata functions to update an existing matplotlib plot. But after updating I want to recenter the plot so that all the points fall into the "view" of the plot.
In the below example, the y data keeps getting bigger but the zoom level of the plot remains same so the data points quickly get out of the scope.
import time
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.ion()
figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
for i in range(1000):
new_y = np.sin(x - 0.5 * i) * i
line1.set_xdata(x)
line1.set_ydata(new_y)
figure.canvas.draw()
figure.canvas.flush_events()
time.sleep(0.1)
Adding ax.relim() and ax.autoscale() fixes the issue
import time
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.ion()
ax: plt.Axes
figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)
ax.autoscale(True)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
for i in range(1000):
new_y = np.sin(x - 0.5 * i) * i
line1.set_xdata(x)
line1.set_ydata(new_y)
# Rescale axes limits
ax.relim()
ax.autoscale()
figure.canvas.draw()
figure.canvas.flush_events()
time.sleep(0.1)
np.sin(x - 0.5 * i) has multiplied by i, which can be 1000. One alternative is to make the y-axis have a limit greater than 1000. So, you can include plt.ylim([-1100,1100]):
import time
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.ion()
figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.ylim([-1100,1100])
for i in range(1000):
new_y = np.sin(x - 0.5 * i) * i
line1.set_xdata(x)
line1.set_ydata(new_y)
figure.canvas.draw()
figure.canvas.flush_events()
time.sleep(0.1)
I want to adjust colobar scale from my current figure1 to the desired figure2 !!
My colorbar scale range is -1 to 1, but I want it in exponential form and for that I tried levels = np.linspace(-100e-2,100e-2) as well, but it also doesn't give the desired scale2
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
ds = xr.open_dataset('PL_Era_Tkt.nc')
wp = ds.w.mean(dim=['longitude','latitude']).plot.contourf(x='time',cmap='RdBu',add_colorbar=False,extend='both')
wpcb = plt.colorbar(wp)
wpcb.set_label(label='Pa.s${^{-1}}$',size=13)
plt.gca().invert_yaxis()
plt.title('Vertical Velocity',size=15)
My current scale
My desired scale
Since the data is not presented, I added normalized color bars with the data from the graph sample here. I think the color bar scales will also be in log format with this setup. Please note that the data used is not large, so I have not been able to confirm this.
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as ticker
import numpy as np
plt.style.use('seaborn-white')
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig, ax = plt.subplots()
ax.contourf(X, Y, Z, 20, cmap='RdGy')
cmap = mpl.cm.RdGy
norm = mpl.colors.Normalize(vmin=-1, vmax=1.0)
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
ax=ax, orientation='vertical', label='Some Units', extend='both', ticks=ticker.LogLocator())
plt.show()
I want to calculate and add R^2 and R in my line chart as a legend, but I only know how to add equations in the chart. Here is my code.My English is poor,I make a mistake in the last question,I don't want to reject your approve.I'm sorry,I hope you can see this question.
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
y = df["rain"]
x = df["SITE"]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(xlabel='year', ylabel='P', title='rain')
ax.grid()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x), "y--")
plt.plot(x, y, 'og-', label=("y=%.6fx+(%.6f)"%(z[0],z[1])))
plt.legend()
You can calculate and plot R^2 as follows given your code:
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import pylab
y = df["rain"]
x = df["SITE"]
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
r_squared = r2_score(x, y)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(xlabel='year', ylabel='P', title='rain')
ax.grid()
pylab.plot(x,p(x), "y--")
pl.plot(x, y, 'og-', label=("y=%.6fx+(%.6f) - $R^2$=%.6f"%(z[0],z[1], r_squared)))
pl.legend()
You can try "$r^2$" (or any combination in a f-string). The $ renders Latex chars in matplotlib labels:
x = np.arange(0, 100)
y = x**2
plt.figure(figsize=(15,10))
plt.plot(x, y, label="y=$x^2$")
plt.legend()
This question already has answers here:
How to plot a gradient color line in matplotlib?
(7 answers)
Closed 3 years ago.
So I have a normal scatter plot:
import numpy as np
import matplotlib.pyplot as plt
import random
x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x
fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')
plt.show()
that produces a plot something like this
However, I would really like to add a line to scatter and connect these points. It may sound ridiculous since it is easy to follow the points in given case, but imagine if the data would be more scattered and possibly multiple datasets ...
So my goal is to add a line to the scatter above, but the color of the line should change according to value of 'z', the same way scatter plot does. Is that even possible?
EDIT:
The x, y, z provided above is just random data to explain the problem. In reality, you can imagine the points (x, y) coordinates are given from an experiment meaning in general there is no relation between x, y, z or even if it is, it is NOT known upfront.
You can add another scatterplot using np.linspace() function:
import numpy as np
import matplotlib.pyplot as plt
import random
x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x
fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')
# add another scatterplot
x_line = np.linspace(np.min(x), np.max(x), num=1000)
y_line = x_line + np.sin(np.pi * x_line)
z_line = 5 * x_line
plt.scatter(x_line, y_line, c=z_line, s=0.1, cmap='coolwarm')
plt.show()