From the Matplotlib's official website I can get that the function 'ax.set()' can bset attributes.But I haven't known what attributes can I set actually.For instance:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib
fig=plt.figure(
figsize=(15,6),
dpi=120,
)
#definition layout
layout=(2,4)
#create
axes=fig.subplots(*layout)
ax_plot_function=axes[0][0]
ax_scatter=axes[0][1]
#plot the first axes
props = {
'title': 'function_example$f(x)=cos(x)$',
'xlabel': 'X',
'ylabel':'Y',
'xlim':(-(2*np.pi),2*np.pi),
'ylim':(-(np.pi),np.pi),
'grid':True,
}
ax_plot_function.set(**props)
x=np.arange(-(2*np.pi),2*np.pi,0.01)
y=np.cos(x)
ax_plot_function.plot(x,y)
plt.show()
in Line29 happens an error that says
AttributeError: 'AxesSubplot' object has no property 'grid'
So I know that the function 'set()' can not have the attribute 'grid' in Line27,But how can I fix it and What attributes can I set exactly by using the function 'ax.set()'.
Could I get a list of all attributes that can set by the function 'set()'? Or Please tell me where I can find the list.
ax.set() can set the properties defined in class matplotlib.axes.Axes.
There is also set_xxx() api where xxx is also the property in class matplotlib.axes.Axes.
The idea is simple, image you create a Python class and some properties. The related getter and setter method should be defined. Also, the constructor method can take initial values of those properties.
If you want to turn on the grid, use ax.grid(True).
Related
I am having trouble setting up a simple dataclass using a new defaultdict(dict).
If I tell the factory to use 'dict' as below , instantiation fails with typerror collection.defaultdict object is not callable
from collections import defaultdict
from dataclasses import dataclass, field
#dataclass
class ResultSet:
changed: bool = False
mqttdata: defaultdict(dict) = field(default_factory=defaultdict(dict)) # does not work!
It does sorta work using field(default_factory=defaultdict) but then my code will fail later when it encounters missing keys - presumably because defaultdict was not set up for dict.
How do I properly set up a new defaultdict(dict) in a dataclass?
You have a few problems with the code and how you are using dataclasses currently:
Type generics in annotations need to be specified through square brackets [] generally, so default[dict] instead of defaultdict(dict) for example.
The default_factory argument to dataclasses.field() needs to be a no-arg callable which returns a new object with default values set. For example, assuming you have a nested dataclass Inner which specifies defaults for all fields, you could use default_factory=Inner to create a new Inner object each time the main dataclass is instantiated.
Note that the default_factory argument is mainly useful for mutable types
such as set, list, and dict, so that the same object isn't
shared (and potentially mutated) between dataclass instances.
Putting it all together, here is the working code which sets a default value for a field of type defaultdict[dict]:
from collections import defaultdict
from dataclasses import dataclass, field
#dataclass
class ResultSet:
changed: bool = False
mqttdata: defaultdict[dict] = field(default_factory=lambda: defaultdict(dict)) # works!
print(ResultSet())
In Python versions earlier than 3.9, which is when PEP 585 was introduced, you'll need to add the following import at the top so that any type annotations are lazy-evaluated:
from __future__ import annotations
I am trying to create a function in which i want to pass pandas dataframe's column name.
Basically i am using plotly.express and that is what i am embedding into a function.
But when i am doing so, it is saying that plotly requires column name but no colomn name found.
def bar(df,**kwargs):
val=", ".join(f"{key}={value}" for key, value in kwargs.items())
px.bar(df,val).show()
bar(sales,x='Category',y='Quantity')```
How can i solve this.
So that whenever user passes an argument it consider it as a field not just a string.
Any leads will be helpful.
TIA
This is not really a plotly question, but python. Fundamentals of how argument passing works.
Simply you just need to pass the kwargs pass to your function to px.bar()
import plotly.express as px
import pandas as pd
import numpy as np
def bar(df,**kwargs):
px.bar(df,**kwargs).show()
sales = pd.DataFrame({"Category":np.random.choice(list("ABCD"), 20), "Quantity":np.random.randint(1,10,20)})
bar(sales,x='Category',y='Quantity')
I am trying to view the imported data through pandas, however when I run the script I am presented with the error "int' object has no attribute 'iloc". I am new here and this is my first post so apologies if I don't know the rules. My code is below.
import pandas as pd
from matplotlib import pyplot
from pandas import read_csv
filename = '/Users/rahulparmeshwar/Documents/Algo Bots/Data/Live Data/Tester.csv'
data = read_csv(filename)
pd.set_option('display.width',100)
pd.DataFrame.head(1)
print(pd)
I am new to Python too.
You want to call head() on your dataframe data, not on the constructor pd.DataFrame.
data = read_csv(filename)
pd.set_option('display.width',100)
print(data.head(1))
The code below complains that vtk.vtkOBJReader() object has no method SetFileNameMTL().
In the documentation it appears to exist vtkOBJImporter.SetFileNameMTL (Maybe the python wrapper for this is missing?).
How can the material (.mtl) for the object be set when parsing the (.obj) in vtk and made visible in k3d?
import k3d
import vtk
import ipywidgets as widgets
reader = vtk.vtkOBJReader()
reader.SetFileName('sample_obj/Model.obj')
reader.SetFileNameMTL('sample_obj/Model.mtl') #Attribute not found
reader.Update()
plot = k3d.plot()
poly_data = reader.GetOutput()
plot += k3d.vtk_poly_data(poly_data)
plot.display()
You are using vtkOBJReader, not vtkOBJImporter. Those are two different classes. vtkOBJReader is the older class, I think, and only reads in the geometry file. To load the material info, you need to use vtkOBJImporter.
Here is an example of what happens:
#dataclass
class D:
prop1: str
prop2: dict = field(default_factory=lambda: defaultdict(set))
d = D("spam")
print(d)
# D(prop1='spam', prop2=Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object at 0x10274c650>,default_factory=<function D.<lambda> at 0x103ad3a70>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=None))
As you can see, the prop2 was not initialized using a default value from the default_factory, it is still a field. And if I try to do d.prop2["some key"] I get TypeError: 'Field' object is not subscriptable.
You probably have imported the dataclass decorator from the wrong module. It may happen if you use automatic imports in your IDE.
The behaviour described happens when you import dataclass from attr (from attr import dataclass).
If you do from dataclasses import dataclass everything will work as expected (the default_factory will be called to generate the value of the field).