Reputation: 113
How can I change the location of a "matplotlib.collections.PolyCollection"?
I have created a PolyCollection, then I want to changed the location.
%matplotlib notebook
import matplotlib.pyplot as plt
p=plt.figure()
area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25)
type(area)
The document is here: https://matplotlib.org/api/collections_api.html#matplotlib.collections.PolyCollection
I think set_offsets() is the funtion to change the position. But I can not find example.
I have tried
area.set_offsets([[1.1, 2.1]])
have no effect.
Upvotes: 1
Views: 676
Reputation: 339300
The PolyCollection created by fill_between does not use any offset. It is simply a Collection of Paths in data coordinates. Three possible ways to update the "position" of the PolyCollection that is created via fill_between
:
In case you want to set an offset in data coordinates you need to tell it to apply this offset in data coordinates via area.set_offset_position("data")
import numpy as np
import matplotlib.pyplot as plt
p=plt.figure()
area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25)
area.set_offsets(np.array([[1.1, 2.1]]))
area.set_offset_position("data")
plt.show()
You may change the Path if you like:
import numpy as np
import matplotlib.pyplot as plt
p=plt.figure()
area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25)
offset = np.array([1.1, 2.1])
area.get_paths()[0].vertices += offset
plt.gca().dataLim.update_from_data_xy(area.get_paths()[0].vertices)
plt.gca().autoscale()
plt.show()
import numpy as np
import matplotlib.transforms
import matplotlib.pyplot as plt
p=plt.figure()
area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25)
offset = np.array([1.1, 2.1])
transoffset = matplotlib.transforms.Affine2D().translate(*offset)
area.set_transform(transoffset + area.get_transform())
plt.show()
Upvotes: 2