AttributeError: 'numpy.ndarray' object has no attribute '_hold' - numpy

I am using numpy and matplotlib in Python3.
The following code is causing the error:
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.axes import Subplot as plt
from matplotlib import pylab
a=[1,1]
b=[1,1]
fsam = 48000
w, h = freqz(b, a, worN=2000)
plt.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
The actual error with matplotlib 1.3.x:
File "/usr/local/lib/python3.2/dist-packages/matplotlib-1.3.x-py3.2-linux-x86_64.egg/matplotlib/axes.py", line 4119, in plot
if not self._hold:
AttributeError: 'numpy.ndarray' object has no attribute '_hold'
The actual error with matplotlib 1.2.0:
Traceback (most recent call last):
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 222, in <module>
main()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 216, in main
form = AppForm()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 39, in __init__
self.on_draw()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 80, in on_draw
self.transfer = Transfer(self.canvas)
File "/home/christoph/audio_measurement/AudioTools/Transfer.py", line 42, in __init__
plt.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
File "/usr/local/lib/python3.2/dist-packages/matplotlib/axes.py", line 3995, in plot
if not self._hold: self.cla()
AttributeError: 'numpy.ndarray' object has no attribute '_hold'
Transfer is the class, which plots onto the canvas.
I had a look at the length of the coefficients a and b, but they did not effect the result.
I could not find anything on that. Does anyone know whats going wrong?

Normally I'd use import matplotlib.pyplot as plt with plt.plot, plt.subplot, plt.show, etc -- or even just from pylab import *. Anyway, this line
from matplotlib.axes import Subplot as plt
is the reason you have an unbound plot function that's trying to operate on the ndarray argument. Subplot needs to be instantiated. This should work:
import numpy as np
from scipy.signal import freqz
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
fig = Figure()
ax = Subplot(fig, 111)
fig.add_subplot(ax)
canvas = FigureCanvas(fig)
a=[1,1]
b=[1,1]
fsam = 48000
w, h = freqz(b, a, worN=2000)
ax.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
canvas.show()

Related

"im2col_out_cpu" not implemented for 'Byte'

I am trying to generate overlap patches from image size (112,112) but i am unable to do so. I have already tried a lot but it didn't work out.
**Code**
import torch
import numpy as np
import torch.nn as nn
from torch import nn
from PIL import Image
import cv2
import os
import math
import torch.nn.functional as F
import torchvision.transforms as T
from timm import create_model
from typing import List
import matplotlib.pyplot as plt
from torchvision import io, transforms
from utils_torch import Image, ImageDraw
from torchvision.transforms.functional import to_pil_image
IMG_SIZE = 112
# PATCH_SIZE = 64
resize = transforms.Resize((IMG_SIZE, IMG_SIZE))
img = resize(io.read_image("Adam_Brody_233.png"))
img = img.to(torch.float32)
image_size = 112
patch_size = 28
ac_patch_size = 12
pad = 4
img = img.unsqueeze(0)
soft_split = nn.Unfold(kernel_size=(ac_patch_size, ac_patch_size), stride=(patch_size, patch_size), padding=(pad, pad))
patches = soft_split(img).transpose(1, 2)
fig, ax = plt.subplots(16, 16)
for i in range(16):
for j in range(16):
sub_img = patches[:, i, j]
ax[i][j].imshow(to_pil_image(sub_img))
ax[i][j].axis('off')
plt.show()
Traceback
Traceback (most recent call last):
File "/home/cvpr/Documents/OPVT/unfold_ours.py", line 32, in <module>
patches = soft_split(img).transpose(1, 2)
File "/home/cvpr/anaconda3/envs/OPVT/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/cvpr/anaconda3/envs/OPVT/lib/python3.7/site-packages/torch/nn/modules/fold.py", line 295, in forward
self.padding, self.stride)
File "/home/cvpr/anaconda3/envs/OPVT/lib/python3.7/site-packages/torch/nn/functional.py", line 3831, in unfold
_pair(dilation), _pair(padding), _pair(stride))
RuntimeError: "im2col_out_cpu" not implemented for 'Byte'
Yes this is an open issue in PyTorch. A simple fix is just to convert your image tensor from ints to floats you can do it like this:
img = img.to(torch.float32)
This should solve your problem

Latex \large use in matplotlib

How can I increase the size of \bullet and \blacktriangledown in matplotlib plot for additional text in the legend? I have
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import fig
... [functions]
plt.xlabel("X-label")
plt.xlabel("Y-label")
plt.legend(['8 $\\times (x+y^2)$'],
title=$\\bullet$ syst. A \n $\\bigblacktriangledown$ syst. B,
loc='center left', bbox_to_anchor=(1.02, 0.5))
plt.savefig("05042022.pdf", bbox_inches="tight")
and if I use \bigblacktriangledown I get the error Unknown symbol: \bigblacktriangledown, found u'\' (at char 0), (line:1, col:1) and if I use \large, I get:
Unknown symbol: \large, found u'\' (at char 1), (line:1, col:2).

ModuleNotFoundError: No module named 'plotly.validators.bar._xaxis' when using plotly

I am trying to plot graphs using the Plotly library. where the x-axis is "interval" and two y-axes " y1-sum " and "y2-average" but I am getting below error.
ERROR:
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-418-27dc9ac84c2a> in <module>
1 from plotly.subplots import make_subplots
2 fig = make_subplots(specs=[[{"secondary_y": True}]])
----> 3 fig.add_trace(fig1.data[0], secondary_y=False)
4 fig.add_trace(fig2.data[0], secondary_y=True)
5 fig.update_layout(width=700, height=450, hovermode='x')
ModuleNotFoundError: No module named 'plotly.validators.bar._xaxis'
The code I am using is as below
import numpy as np
import pandas as pd
import plotly.graph_objects as go
df1 = pd.read_csv('C:/Users/Desktop/y1_data.csv')
df2 = pd.read_csv('C:/Users/Desktop/y2_data.csv')
fig1 =go.Figure([go.Bar(x=df2['Interval'], y=df1['sum'], name='iops')])
fig2 =go.Figure([go.Scatter(x=df2['Interval'], y=df2['Average'], name='latency')])
from plotly.subplots import make_subplots
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(fig1.data[0], secondary_y=False)
fig.add_trace(fig2.data[0], secondary_y=True)
fig.update_layout(width=700, height=450, hovermode='x')
fig.show()
Need Graph like above.
sample_data_iops
sample_data_lat
Currently using Plotly 4.x version. Can anyone let me know how this can be done?
I created the following code with the understanding that your question was intended to draw two axes in one graph, rather than multiple graphs. I don't have sample data, so I haven't been able to check the execution in my environment, but you can specify the graph and the y-axis at the same time. Please refer to this.
import numpy as np
import datetime
import pandas as pd
import plotly.graph_objects as go
df1 = pd.read_csv('C:/Users/Desktop/y1_data.csv')
df2 = pd.read_csv('C:/Users/Desktop/y2_data.csv')
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Bar(x=df2['Interval'], y=df1['sum'], name='io_rate data'),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=df2['Interval'], y=df2['Average'], name='latency data'),
secondary_y=True,
)
fig.update_layout(width=700, height=450, hovermode='x')
fig.update_yaxes(title_text="<b>primary</b> io_rate", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> latency", secondary_y=True)
fig.show()

Array is not iterable, but how to use as argument in zip()?

I want to plot 3D visualizations of DICOM Scans, but I am stuck on this error.
I am using the marching cubes method. First from mesh verts and faces and returned then passed into plt_3d. Modules imported:
import numpy as np
import pydicom as pyd
import os
import matplotlib.pyplot as plt
from glob import glob
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import scipy.ndimage
from skimage import morphology
from skimage import measure
from skimage.transform import resize
from sklearn.cluster import KMeans
from plotly import version
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.tools import FigureFactory as FF
from plotly.graph_objs import *
init_notebook_mode(connected=True)
imgs_after_resamp is the pixel array(3d) which contains the DICOM Data
def make_mesh(image, threshold=-300, step_size=1):
p = image.transpose(2,1,0)
verts, faces, norm, val = measure.marching_cubes_lewiner(p, threshold,
step_size=step_size, allow_degenerate=True)
print(verts)
return verts, faces
def plotly_3d(verts, faces):
x,y,z = zip(*verts)
fig = FF.create_trisurf(x=x,
y=y,
z=z,
plot_edges=False,
colormap=colormap,
simplices=faces,
backgroundcolor='rgb(64, 64, 64)',
title="Interactive Visualization")
iplot(fig)
def plt_3d(verts, faces):
print(“Drawing”)
x,y,z = zip(*verts)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
mesh = Poly3DCollection(verts[faces], linewidths=0.05, alpha=1)
face_color = [1, 1, 0.9]
mesh.set_facecolor(face_color)
ax.add_collection3d(mesh)
ax.set_xlim(0, max(x))
ax.set_ylim(0, max(y))
ax.set_zlim(0, max(z))
ax.set_axis_bgcolor((0.7, 0.7, 0.7))
plt.show()
v, f = make_mesh(imgs_after_resamp, 350)
new3d=np.vectorize(plt_3d)
new3d(v,f)
ValueError Traceback (most recent call last)
in
----> 1 plot_ve(imgs_re,400)
TypeError: type object argument after * must be an iterable, not numpy.float32

name "plot" is not defined

I'm trying to plot some data using matplotlib with the code below.
import matplotlib.pyplot as plt
import numpy as np
data_x = np.linspace(0, 10, 100)
data_y = 10 * np.exp(-data_x)
np.savetxt('tabelle1.txt', np.column_stack([data_x, data_y]), header='U I')
x, y = np.genfromtxt('tabelle1', unpack=True)
plt.plot(x, y, 'rx')
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.yscale('log')
plt.tight_layout()
plt.savefig('loesung.pdf')
However, this generates an error saying NameError: name plot is not defined.
How can I fix this?
please try
#Add this script
import matplotlib
#Before
import matplotlib.pyplot as plt