-
-
Notifications
You must be signed in to change notification settings - Fork 7.9k
matplotlib.units.ConversionError on scatter of dates with a NaN in the first position #14356
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Minimizing this would be helpful because the following works fine: import matplotlib.pyplot as plt
import numpy as np
f, ax = plt.subplots()
times = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
y = np.linspace(0, 10, len(times))
y[3] = 1
y[10] = 1
y[21] = 1
ax.scatter(times, [x if x != 1 else np.nan for x in y], color='b', marker='o')
plt.show() |
I managed to find a minimal example: import numpy as np
import pylab as plt
times = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
y = np.random.random(size=len(times))
y[0] = np.nan
plt.scatter(times, y)
plt.show() It fails when the first number on the y values in the scatter is a nan, and the x values are dates. |
Looks like diff --git i/lib/matplotlib/units.py w/lib/matplotlib/units.py
index b4677bdd3..d77ed8c5b 100644
--- i/lib/matplotlib/units.py
+++ w/lib/matplotlib/units.py
@@ -123,34 +123,38 @@ class ConversionInterface:
@staticmethod
def is_numlike(x):
"""
The Matplotlib datalim, autoscaling, locators etc work with scalars
which are the units converted to floats given the current unit. The
converter may be passed these floats, or arrays of them, even when
units are set.
"""
if np.iterable(x):
for thisx in x:
+ if thisx is ma.masked:
+ continue
return isinstance(thisx, Number)
else:
return isinstance(x, Number)
@staticmethod
def is_natively_supported(x):
"""
Return whether *x* is of a type that Matplotlib natively supports or
*x* is array of objects of such types.
"""
# Matplotlib natively supports all number types except Decimal
if np.iterable(x):
# Assume lists are homogeneous as other functions in unit system
for thisx in x:
+ if thisx is ma.masked:
+ continue
return (isinstance(thisx, Number) and
not isinstance(thisx, Decimal))
else:
return isinstance(x, Number) and not isinstance(x, Decimal)
class DecimalConverter(ConversionInterface):
"""
Converter for decimal.Decimal data to float.
""" fixes the issue as of master, which makes sense. (No tests provided :p) There are some more questions, e.g. if Also only the change to is_natively_supported is necessary here, but I think the change to is_numlike is likely necessary in other cases too. |
This works fine for plot, so yet again its a case of |
This is part of the work on scatter to make it handle updates to datasets that initially had some missing data more gracefully. With plot we always have exactly 2 vectors to work with, with scatter we have up to 4 (x, y, size, color). |
The bug is still there when everything is NaN:
|
I would expect it to behave as it does for individual nans: not plot anything. Background of my motivation: I am using NaNs to mask away data points that I want to have in different alphas. Usually, every plot contains both, so it works, but today I found one where all of them were of the same kind, and the other was fully masked. I have added a check to skip it alltogether, but it used to work on earlier versions of Matplotlib, so it should still work. |
fig,ax= plt.subplots(figsize=(15,5)) ax.plot(consum_test.index,consum_test["PJME_MW"],label="Actual") consum = consum_test["PJME_MW"] plt.fill_between(consum_test.index, consum,pred, facecolor="green", alpha=.2,label="Difference") ax.set_ylim(25000, 45000) plt.xlabel("Date", alpha=0.75, weight="bold") plt.xticks(alpha=0.75,weight="bold", fontsize=11) plt.title("Period with the worst hourly prediction", alpha=0.75, weight="bold", fontsize=15, pad=10, loc="left") ========================================================================= this is my code and giving error IndexError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\matplotlib\dates.py in convert(value, unit, axis) ~\Anaconda3\lib\site-packages\matplotlib\dates.py in date2num(d) IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed The above exception was the direct cause of the following exception: ConversionError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\matplotlib\axes_base.py in set_xbound(self, lower, upper) ~\Anaconda3\lib\site-packages\matplotlib\axes_base.py in set_xlim(self, left, right, emit, auto, xmin, xmax) ~\Anaconda3\lib\site-packages\matplotlib\axes_base.py in _validate_converted_limits(self, limit, convert) ~\Anaconda3\lib\site-packages\matplotlib\artist.py in convert_xunits(self, x) ~\Anaconda3\lib\site-packages\matplotlib\axis.py in convert_units(self, x) ConversionError: Failed to convert value(s) to axis units: '2017-03-12 00:00:00' |
how i can solve plz help |
@wardafiaz please take user help to https://discourse.matplotlib.org! (but "2017-03-12 00:00:00" is a string. Convert to a date to use it as an limit). |
Could anyone provide solution to this problem? thanks in advance |
This issue is closed. Can you post a new issue with a self-contained example? Thanks... |
Actually i had same error last time , but after searching couple of hours i
get the solution of my problem
…On Mon, 17 Jan 2022 at 22:02, Jody Klymak ***@***.***> wrote:
This issue is closed. Can you post a new issue with a self-contained
example? Thanks...
—
Reply to this email directly, view it on GitHub
<#14356 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ASTICS33JEV6E6FP2VMATT3UWRABBANCNFSM4HQGQCZA>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you commented.Message ID:
***@***.***>
|
Hey @Adi07-Nerd, where did you found a solution to your problem. I have expended a good couple of hours already trying to fix the issue below:
plotting within for loop, only first df is plotted. error comes after: ConversionError: Failed to convert value(s) to axis units: 0 2022-10-27 10:30:00 Any help would be greatly appreciated. |
@charlie83xt Can you please open a new issue with that example + enough (synthetic) data to reproduce the issue? |
Bug report
Bug summary
When on a scatter plot the first number on the y values is a nan, and the x values are dates, I get the error:
matplotlib.units.ConversionError: Failed to convert value(s) to axis units: masked_array
Code for reproduction*
Actual outcome
On Matplotlib 3.0.0, I get no warning.
On 3.1.0, I get an error.
Matplotlib version
print(matplotlib.get_backend())
): Qt5AggMatplotlib installed through pip on a virtual environment
The text was updated successfully, but these errors were encountered: