has2k1 / plotnine

A Grammar of Graphics for Python
https://plotnine.org
MIT License
4k stars 213 forks source link

ValueError: The truth value of an array with more than one element is ambiguous. #696

Closed pwwang closed 1 year ago

pwwang commented 1 year ago

https://github.com/has2k1/plotnine/blob/2405442dfd59f966ad98a6461ef870ea8e406235/plotnine/scales/scale.py#L1012-L1030

self.minor_breaks could be a numpy array, which is causing this error.

elif self.minor_breaks is False or self.minor_breaks is None or not len(major):

would fix it.

Also, line 1020 should be:

             minor_breaks = self.trans.transform(self.minor_breaks)
has2k1 commented 1 year ago

@pwwang, do you have a simplified example that triggered the error.

pwwang commented 1 year ago

If we generate the minor_breaks using np.array, then the error on the title raised:

import pandas as pd
import plotnine as p9
import numpy as np

df = pd.DataFrame({'x': [1, 10, 100], 'y': [3, 1, 2]})

p = p9.ggplot(df, p9.aes(x='x', y='y')) + p9.scale_x_log10(
    minor_breaks=np.array([10**0.5, 10**1.5, 10**2.5])
#                ^^^^^^^^
)
p  # ValueError

It's fine if we fallback to a list:

import pandas as pd
import plotnine as p9
import numpy as np

df = pd.DataFrame({'x': [1, 10, 100], 'y': [3, 1, 2]})

p = p9.ggplot(df, p9.aes(x='x', y='y')) + p9.scale_x_log10(
    minor_breaks=[10**0.5, 10**1.5, 10**2.5]
)
p  # ValueError

But the minor breaks are wrong:

image

That's why we need to modify line 1020.

There are other similar coding styles in this scale.py:

https://github.com/has2k1/plotnine/blob/2405442dfd59f966ad98a6461ef870ea8e406235/plotnine/scales/scale.py#L573 https://github.com/has2k1/plotnine/blob/2405442dfd59f966ad98a6461ef870ea8e406235/plotnine/scales/scale.py#L1042

I am not sure if there are other similar situations in other files.

I understand you expected them to be plain python objects (list), but sometimes they could be a numpy array or a pandas Series.

pwwang commented 1 year ago

By the way, for now, I have to monkey-patch plotnine to get plotnine-prism to work:

https://github.com/pwwang/plotnine-prism/blob/09804d56614632dddd322fa312e5285dbbbb6243/plotnine_prism/scale.py#L8-L102