I want to change text in matplotlib's plot with loop. I am able to print text with loop, but unable to delete the previous text and they got printed on top of each other.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5])
y = np.array([1,2,3,4,5])
fig, ax = plt.subplots()
ax.set_xlim([0,5])
ax.set_ylim([0,5])
for i in x:
pt = ax.plot(i, i, 'o')
tx = ax.text(1, 2, str(i), fontsize = 12)
plt.pause(1)
removePt = pt.pop()
removePt.remove()
I tried to delete text by
removeTx = tx.pop()
removeTx.remove()
but it has not worked.
Kindly suggest how can I remove the previous text from plot.
Just add tx.remove() after the pause:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 2, 3, 4, 5])
fig, ax = plt.subplots()
ax.set_xlim([0, 5])
ax.set_ylim([0, 5])
for i in x:
pt = ax.plot(i, i, 'o')
tx = ax.text(1, 2, str(i), fontsize = 12)
plt.pause(1)
tx.remove()
plt.show()
Related
I am new in python programming. I can simply plot the input data shown in the figure with my code but how can I plot the time series data as mention in the figure. Any code and suggestions will be thankful.
My code is:
import matplotlib.pyplot as plt
import numpy as np
y_values = [5, 5, 1, 1, 5, 5, 1, 1, 5, 1, 1]
x_values = np.arange(30, 331, 30)
plt.figure()
plt.plot(x_values,y_values,"-x")
plt.show()
Although there is a way to draw a series of rectangular shapes, we used a general method and used horizontal bar charts. We added a list for the values in the bar chart and stacked the values. Class label names and class titles are now supported as annotations. You can try various other parameters.
import matplotlib.pyplot as plt
import numpy as np
y = [5]*11
y_values = [5, 5, 1, 1, 5, 5, 1, 1, 5, 1, 1]
x_values = np.arange(30, 331, 30)
fig, ax = plt.subplots(figsize=(12,1))
ax.barh(y=0, height=1.0, edgecolor='k', width=y[0], label='Time Interval')
for i in range(len(y)):
if y_values[i] == 5:
color = 'y'
else:
color = 'm'
ax.barh(y=0, left=sum(y[:i]), height=1.0, width=y[i], color=color, edgecolor='k', label='Time Interval')
for s in ['top','bottom','left','right']:
ax.spines[s].set_visible(False)
for i,(p,t) in enumerate(zip(y, y_values)):
ax.text(y=0.6, x=2.5+p*i, s=str(t))
ax.text(-0.08, 1, 'Class', transform=ax.transAxes)
ax.set_xticks([])
ax.set_yticks([])
ax.set_ylabel('Time Interval', rotation=0, labelpad=40, loc='center')
plt.show()
Try:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
y_values = ['class', 5, 5, 1, 1, 5, 5, 1, 1, 5, 1, 1]
x_values = np.arange(30, 331, 30)
x_values = np.concatenate((['Time'],x_values))
df = pd.DataFrame(data={'class': y_values, 'Time': x_values})
colors = {5: 'gold', 1: 'darkviolet'}
df['colors'] = df['class'].map(colors)
df['colors'].fillna('white', inplace=True)
df['Time'].iloc[1:] = ''
print(df)
fig, ax =plt.subplots(1,1)
ax.axis('tight')
ax.axis('off')
data = df.T.values
colors = [data[2].tolist()]
table = ax.table(cellText=[data[1].tolist()], colLabels=data[0].tolist(),loc="center", cellColours=colors)
table.set_fontsize(14)
for i in range(len(data[0])):
table[0, i].visible_edges = ''
table[1, 0].visible_edges = ''
table.scale(1.5, 1.5)
plt.show()
def PlotPolly(model, independent_variable, dependent_variabble, Name):
x_new = np.linspace(15, 55, 100)
y_new = model(x_new)
plt.plot(independent_variable, dependent_variabble, '.', x_new, y_new, '-') #4
plt.title('Polynomial Fit with Matplotlib for Price ~ Length')
ax = plt.gca()
ax.set_facecolor((0.898, 0.898, 0.898))
fig = plt.gcf()
plt.xlabel(Name)
plt.ylabel('Price of Cars')
plt.show()
plt.close()
I get this with this code:
But when from line 4 I remove x_new and y_new line becomes
plt.plot(independent_variable, dependent_variabble)
I get this graph :
Can you explain what is meaning of x_new and y_new and why absence of this results in this kind of graph
In your code x_new and y_new both of them have the continuous values but independent_variable and dependent_variabble have ā€¨discontinuous values and for plot discontinues you need scatter plot. see this example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([2, 1, 5, 3, 4, 2, 6, 4])
y = np.array([3, 1, 2, 0, 1, 2, 6, 4])
plt.plot(x, y, linestyle='-', marker='o')
Output:
If I set shade_lowest = False, the colorbar still contains the lowest level (purple-ish). Is there any generic way to remove it entirely?
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0, 1, 100)
b = np.random.normal(0, 1, 100)
fig, ax = plt.subplots()
sns.kdeplot(a, b, shade = True, shade_lowest = False, cmap = "viridis", cbar = True, n_levels = 4, ax = ax)
plt.show()
A solution is for sure to not create this level from the beginning.
Here we choose maximally 5 levels according to a locator and remove the lowest one when calling the contourf plot, such that this level does not even exist in the first place. Then the automatic colorbar creation works flawlessly.
import numpy as np; np.random.seed(5)
import matplotlib.pyplot as plt
from matplotlib import ticker
from scipy import stats
x = np.random.normal(3, 1, 100)
y = np.random.normal(0, 2, 100)
X, Y = np.mgrid[x.min():x.max():100j, y.min():y.max():100j]
positions = np.vstack([X.ravel(),Y.ravel()])
values = np.vstack([x,y])
kernel = stats.gaussian_kde(values)
Z = np.reshape(kernel(positions).T, X.shape)
N=4
locator = ticker.MaxNLocator(N + 1, min_n_ticks=N)
lev = locator.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots()
c = ax.contourf(X,Y,Z,levels=lev[1:])
ax.scatter(x,y, s=9, c="k")
fig.colorbar(c)
plt.show()
I've written a function that reads data from a csv file and plots it. Now I need to add a subplot with another part of the data from the same file, so I've tried to write a function that calls the first function and adds a subplot. When I do this, I get the two to show up as different figures. How can I suppress this and make both of them show in the same figure?
Here is a mockup of my code:
def timex(h_ratio = [3, 1]):
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
total_height = h_ratio[0] + h_ratio[1]
gs = gridspec.GridSpec(total_height, 1)
time = [1, 2, 3, 4, 5]
x = [1, 2, 3, 4, 5]
y = [1, 1, 1, 1, 1]
ax1 = plt.subplot(gs[:h_ratio[0], :])
plt.plot(time, x)
plot = plt.gcf
plt.show()
return time, x, y, plot, gs, h_ratio
def timeyx():
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
time, x, y, plot, gs, h_ratio = timex(h_ratio = [3, 1])
ax2 = plt.subplot(gs[h_ratio[1], :])
plt.plot(time, y)
plt.show()
timeyx()
I realize that I have two plt.show() statements, but if I remove one that figure will not show at all.
I am not sure whether you need to use matplotlib.gridspec specifically or not, but you can use subplot2grid to make the job easy.
import matplotlib.pyplot as plt
def timex():
time = [1, 2, 3, 4, 5]
x = [1, 2, 3, 4, 5]
y = [1, 1, 1, 1, 1]
ax1 = plt.subplot2grid((1,2), (0,0))
ax1.plot(time, x)
return time, x, y
def timeyx():
time, x, y = timex()
ax2 = plt.subplot2grid((1,2), (0,1))
ax2.plot(time, y)
timeyx()
plt.show()
This produces one figure shown below with two subplots:
I'm looking to make a colorbar like plot, like so:
but with a controllable color, for example I have the following x and y arrays:
x = [0,1,2,4,7,8]
y = [1,2,1,3,4,5]
Then I would have a colorbar like the above picture, but when y=1, it would color red, y=2: green, y=3: blue, y=4:black, etc.
Here is the python code that I modified from matplotlib's gallery:
from matplotlib import pyplot
import matplotlib as mpl
fig = pyplot.figure(figsize=(8,1))
ax2 = fig.add_axes([0.05, 0.25, 0.9, 0.5])
cmap = mpl.cm.Accent
norm = mpl.colors.Normalize(vmin=5, vmax=10)
bounds = [1, 2, 4, 7, 8]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
norm=norm,
boundaries=[0]+bounds+[13],
ticks=bounds, # optional
spacing='proportional',
orientation='horizontal')
After adapting your code I managed to obtain something like you described.
In this case the colormap is generated using ListedColormap and I added the yellow color for y=5.
It is important to notice that while calculating the BoundaryNorm I am using the intervals that contain the values you described for y.
from matplotlib import pyplot,colors
import matplotlib as mpl
fig = pyplot.figure(figsize=(8,1))
ax2 = fig.add_axes([0.05, 0.25, 0.9, 0.5])
cmap = colors.ListedColormap(['r', 'g', 'b', 'k','y'])
bounds = [0, 1, 2, 4, 7, 8, 13]
yVals = [ 1, 2, 1, 3, 4, 5]
cBounds = [i+0.5 for i in range(6)]
norm = mpl.colors.BoundaryNorm(cBounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
norm=norm,
values=yVals,
boundaries=bounds,
ticks=bounds[1:-1], # optional
spacing='proportional',
orientation='horizontal')
-- Edited 14 of Jan (mrcl) --
Alternatively, you can use pcolormesh to plot your colormap and have a colorbar as your legend, such as in the example below.
from pylab import *
from matplotlib import pyplot,colors
import matplotlib as mpl
fig = pyplot.figure(figsize=(8,1.5))
ax1 = fig.add_axes([0.05, 0.25, 0.82, 0.5])
cmap = colors.ListedColormap(['r', 'g', 'b', 'k','y'])
xBounds = array([0, 1, 2, 4, 7, 8, 13])
yBounds = array([0, 1])
Vals = array([[ 1, 2, 1, 3, 4, 5]])
cBounds = [i+0.5 for i in arange(amax(Vals)+1)]
norm = mpl.colors.BoundaryNorm(cBounds, cmap.N)
c = ax1.pcolormesh(xBounds,yBounds,Vals,cmap=cmap,norm=norm)
ax1.set_xticks(xBounds[1:-1])
ax1.set_yticks([])
ax1.set_xlim(xBounds[0],xBounds[-1])
ax1.set_ylim(yBounds[0],yBounds[-1])
ax2 = fig.add_axes([0.9, 0.25, 0.05, 0.5])
colorbar(c,cax=ax2,ticks=arange(amax(Vals))+1)
Hope it helps.
Cheers
Well, I sort of tinkering with other ways:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import matplotlib.colors as colors
close('all')
def ColorPlot(x,y):
figure()
jet = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=min(y), vmax=max(y))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
if len(x) == len(y):
x.insert(0,0)
for kk in range(len(x)-1):
colorVal = scalarMap.to_rgba(y[kk])
plt.axvspan(x[kk], x[kk+1], facecolor=colorVal,
alpha=0.5,label=colorVal)
plt.yticks([])
plt.xticks(x)
xlim([x[0],x[-1]])
plt.show()
x = [1,3,5,6,10,12]
y = [1,3,4,1,4,3]
ColorPlot(x,y)