plt.show() not working in spyder 3.7(Anaconda 3) - python-3.x

I am new to Python and Spyder. I am using Python 3.7 (Anaconda 3). I cannot get my graph after labelling x & y axis using plt.show() & also plt.draw() does not work either.
import os
import numpy as np
import matplotlib.pyplot as plt
time=[1,2,4]
data_list_Ch4=[1,3,5]
plt.plot(time, data_list_Ch4)
plt.xlabel("Time")
plt.ylabel("Channel")
plt.show()
screen shot of Spyder ide

Related

Plotly express not showing plots in PyCharm SciView

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

How do I make my plot look like this with matplotlib?

So right now I'm trying to simulate a Poisson process for an assignment, here's the code so far:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
y = np.arange(0,21,1)
x = np.cumsum(np.random.exponential(2,21))
print(y)
print(x)
sns.set()
plt.plot(x,y)
plt.show()
The problem arises when I try plotting it. The code above, as expected, produces a normal matplotlib plot that looks like this:
However I need it to look like this:
Is there an easy way of doing it? I tried messing with bar plots but was unable to produce something that looks good.
The graph that you are wanting to plot is called as step plot in matplotlib. In order to plot it replace plt.plot(x,y) with plt.step(x,y)
So, your code becomes:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
y = np.arange(0,21,1)
x = np.cumsum(np.random.exponential(2,21))
print(y)
print(x)
sns.set()
plt.step(x,y)
plt.show()

Matplotlib.plot not found

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)

How can I solve " module 'pandas' has no attribute 'scatter_matrix' " error?

I'm trying to run pd.scatter_matrix() function in Jupyter Notebook with my code below:
import matplotlib.pyplot as plt
import pandas as pd
# Load some data
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])
iris_df['species'] = iris['target']
pd.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
But I'm getting
AttributeError: module 'pandas' has no attribute 'scatter_matrix'.
Even after executing conda update pandas and conda update matplotlib commands in Terminal, this is still occurring.
I executed pd.__version__ command to check my pandas version and it's '0.24.2'. What could be the problem?
This method is under pandas.plotting - docs and pandas.plotting.scatter_matrix:
from pandas.plotting import scatter_matrix
scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
Another option is keeping only pandas import and rewriting the command scatter_matrix, like in the example below:
import pandas as pd
pd.plotting.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
Using
from pandas.plotting._misc import scatter_matrix
don't use pd.scatter_matrix or pandas.scatter_matrix
you can directly call scatter_matrix
e.g.
cmap = cm.get_cmap('gnuplot')
scatter = scatter_matrix(X, c = y, marker = 'o', s=40, hist_kwds={'bins':15},
figsize=(9,9), cmap = cmap)
plt.suptitle('Scatter-matrix for each input variable')
plt.savefig('fruits_scatter_matrix')
plt.show()
Use:
from pandas.plotting import scatter_matrix
The code becomes:
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])
iris_df['species'] = iris['target']
scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
In our case we were executing below code "axs = pd.scatter_matrix(sampled_data, figsize=(10, 10)) "
so the error clearly says scatter_matrix is not available in pandas
Solution:
A bit of google and we found scatter_matrix is available in pandas.plotting
So correct code is "axs = pd.plotting.scatter_matrix(sampled_data, figsize=(10, 10)) "
I used
from pandas.plotting import scatter_matrix
and called scatter_matrix directly worked like charm.

interact and plotting with ipywidgets events produces many graphs

I am trying to use widget events to make an interactive graph.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
def myplot(n):
x = np.linspace(-5, 5, 30)
y = x**n
fig, ax = plt.subplots(nrows=1, ncols=1);
ax.plot(x, y)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
Interact works as expected (it changes the figure interactively):
widgets.interact(myplot, n=(0,5));
However the following snippet creates several figures that appear below as you interact with the slider.
n_widget = widgets.IntSlider(
value=2,
min=0,
max=5)
def on_value_change(change):
myplot(n=n_widget.value)
n_widget.observe(on_value_change)
display(n_widget)
Can I update the plot as if I were using widgets.interact()?
My current installation is with conda and Python 3.6 (windows machine).
ipywidgets 7.1.0
jupyter 1.0.0
jupyter_client 5.2.1
jupyter_console 5.2.0
jupyter_core 4.4.0
matplotlib 2.1.1
notebook 5.3.1
numpy 1.14.0
Note that the below is a working solution for ipywidgets version < 7.0. For a solution with ipywidgets >= 7.0 see this GitHub issue.
While in many simple cases plt.show() works nicely replacing the output of a cell, this is not always the case. When using interactive elements in Jupyter it is often more helpful to use IPython.display.display.
Here you may not want to create a new plot for each interaction. Instead just setting new data to the plot is enough. Then you may autoscale the plot for the new data and display the figure. You may use IPython.display.clear_output to clear the output once a new figure would be displayed. This ensures to have always a single plot present in the output cell, independent of the use of interact or observe.
def myplot(n):
line.set_ydata(x**n)
ax.relim()
ax.autoscale()
display(fig)
clear_output(wait=True)
Comlpete notebook:
# cell 1
%%capture
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
import ipywidgets as widgets
fig, ax = plt.subplots(nrows=1, ncols=1);
x = np.linspace(-5, 5, 30)
y = x**0
line, = ax.plot(x, y)
ax.set_xlabel('x')
ax.set_ylabel('y')
def myplot(n):
line.set_ydata(x**n)
ax.relim()
ax.autoscale()
display(fig)
clear_output(wait=True)
#cell2
widgets.interact(myplot, n=(0,5));
#cell3
n_widget = widgets.IntSlider(
value=2,
min=0,
max=5)
def on_value_change(change):
myplot(n=n_widget.value)
n_widget.observe(on_value_change)
display(n_widget)

Resources