I need to use TkAgg backend in matplotlib to plot on my machine (A) while calculating via ssh in another machine (B).
Following other questions like this, I do:
import matplotlib
matplotlib.use('TkAgg')
matplotlib.get_backend() # prints: 'TkAgg'
import matplotlib.pyplot as plt
matplotlib.get_backend() # prints: 'agg'
# Plotting...
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
plt.plot(t, s)
plt.show()
But gives the error:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
It seems that every time I import matplotlib.pyplot it switches back to the default backend!
What do I need to do?
Related
I am using statsmodels.api.tsa.seasonal_decompose to do some seasonal analysis of a time series.
I set it up using
decomp_viz = sm.tsa.seasonal_decompose(df_ts['NetConsumption'], period=48*180)
and then try and visualise it using
decomp_viz.plot()
The output was tiny so I tried to use the standard matplotlib command of
decomp_viz.plot(figsize=(20,20))
However, this got the warning:
TypeError: plot() got an unexpected keyword argument 'figsize'
The documentation says that a matplotlib.figure.Figure is returned from DecomposeResult.plot so I am unsure as to why this error is happening.
My version of statsmodels is 0.13.1 and I am aware that the documentation is for 0.14.0, but conda says that that version does not exist and that I cannot update to it.
Any thoughts would be appreciated.
DecomposeResult.plot doesn't pass keyword arguments. You can change the figure size after you create it:
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
PERIOD = 48*180
g = np.random.default_rng(20211225)
y = np.cos(2 * np.pi * np.linspace(0, 10.0, 10*PERIOD))
y += g.standard_normal(y.shape)
decomp_viz = sm.tsa.seasonal_decompose(y, period=PERIOD)
fig = decomp_viz.plot()
fig.set_size_inches((16, 9))
# Tight layout to realign things
fig.tight_layout()
plt.show()
Alternatively, you can do the same by altering the MPL rc.
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
# Change default figsize
plt.rc("figure",figsize=(20,20))
PERIOD = 48*180
g = np.random.default_rng(20211225)
y = np.cos(2 * np.pi * np.linspace(0, 10.0, 10*PERIOD))
y += g.standard_normal(y.shape)
decomp_viz = sm.tsa.seasonal_decompose(y, period=PERIOD)
decomp_viz.plot()
plt.show()
which produces (cropped as too big for my screen)
I'm trying to render a Plotly graph in PyCharm's SciView-Plots panel (using PyCharm Professional 2020.3).
A simplified version of what I'm running is:
import plotly.express as px
import plotly.io as pio
pio.renderers.default = 'png'
fig = px.scatter(data)
fig.show()
This code runs, but does not show a plot. Instead I see a printout in the console that looks like:
{'image/png': 'iVBORw0KGgoAAAANSUh<cropped for brevity...>'}
I was working on following this article, but the solutions there don't seem to work: how can I see plotly graphs in pycharm?
Sciview will support matplotlib.pyplot.show, therefore you can export to png, then display the png using matplotlib.pyplot.show
import io
import numpy as np
import plotly.express as px
import plotly.io as pio
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
pio.renderers.default = 'png'
def plot(fig):
img_bytes = fig.to_image(format="png")
fp = io.BytesIO(img_bytes)
with fp:
i = mpimg.imread(fp, format='png')
plt.axis('off')
plt.imshow(i, interpolation='nearest')
plt.show()
x = np.arange(0, 5, 0.1)
y = np.sin(x)
fig = px.scatter(x, y)
plot(fig)
works with Pycharm professional 2019.3
I'm attempting to hide the y-axis labels on a matplotlib axis. There seems to be an error that some of the labels are hidden but others are not. Is this a bug and is there a way to turn off all the labels? Is it the way that I'm plotting?
Note: I'm only showing half my plot the other half is a cartopy map.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.img_tiles import Stamen
import cartopy.io.shapereader as shpreader
from cartopy.feature import ShapelyFeature
import os
import pickle
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
from pathlib import Path
fig=plt.figure(figsize=(16,9), dpi=300, constrained_layout=True)
gs0=fig.add_gridspec(1,2)
gs00=gs0[0].subgridspec(10,1)
gs01=gs0[1].subgridspec(1,1)
data_dir='/data/files/'
ext_=f'*.pkl'
p=Path(data_dir).glob(ext_)
s=[str(i) for i in p]
for i,j in enumerate(s):
ax=fig.add_subplot(gs00[i,0])
f=pickle.load(open(j, 'rb'))
ax.loglog(f[0], f[2])
ax.margins(x=0)
ax.set_yticklabels([])
ax2=fig.add_subplot(gs01[0,0], projection=ccrs.PlateCarree())
I think you can use plt.tick_params()
See explainations from this topic Remove xticks in a matplotlib plot?
Modification for y-axis:
from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
axis='y', # changes apply to the y-axis
which='both', # both major and minor ticks are affected
left=False, # ticks along the left edge are off
labelleft=False) # labels along the left edge are off
plt.show()
I installed Matplotlib via Anaconda from here: https://anaconda.org/conda-forge/matplotlib
I used the very first command in Anaconda prompt.
But when I tried to plot from python (Spyder) as the following, I get the message:
ModuleNotFoundError: No module named 'matplotlib.plot'
import numpy as np
import matplotlib.plot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x,y)
I have installed numpy, pandas and such using the same method and they work well.
How can I fix this?
Thank you so much.
matplotlib.pyplot is a state-based interface to matplotlib. pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation. Therefore, whenever trying to work with graphs and what is commonly known and informally often referred as matplotlib you should import matplotlib.pyplot as plt:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x,y)
So I was trying to map out some math functions in 3d using matplotlib when I noticed something... The 3d plot suddenly changed (more like broke) when I tried to fix a previous issue wherein I was encountering some 'missing surface' - a gap in the plot. The main question is this -- Is the 3d plot not showing the two peaks on higher precision due to some inherent computing limitations of Axes3d or some other reason? Also a secondary question -- Why am I encountering 'missing surfaces' near +1.25 and -1.25 in lower precision plot?
I have tried googling for it and referred a few posts but nothing came ot except more questions.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X=np.arange(-2,+2,0.025)
## Use np.arange(-5,+5,0.25) to experience the 'surface loss' I mention but otherwise correct 2 spike plot at each of (0,-1) and (0,+1) for both X and Y
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
R=1+X**2-Y**2
S=R**2+4*(X**2)*(Y**2)
Z=R/S
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
##NORMALIZE Was essential to get the proper color range
plt.show()
plt.savefig('art3d.jpeg',bbox_inches='tight')
plt.savefig('art3d.svg',bbox_inches='tight')
The ideal result should be like this (shows the func and the plot)
https://i.stack.imgur.com/kVnYc.png
The two plots I'm getting could be seen when the code is run as I can't seem to add images presumably because of low reputation :(
Any and all help is appreciated.Thanks in advance.
First note that the function in use is different from the wolfram alpha output. So let's use the function shown in the screenshot. Then you can limit the data to the range you want to show.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-2,+2,0.025)
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
Z = -2*X*Y / ((2*X*Y)**2 + (X**2 - Y**2 + 1)**2)
Z[(Z < -1)] = -1
Z[(Z > 1)] = 1
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
plt.show()