ValueError当将颜色数组传递给stripplot时。

huangapple go评论88阅读模式
英文:

ValueError when passing array of colors to a stripplot

问题

以下是代码的翻译部分:

  1. import pandas as pd
  2. import numpy as np
  3. import seaborn
  4. from matplotlib import pyplot as plt
  5. THRESHOLD = 0.5
  6. data = pd.DataFrame({
  7. "Group": ["1", "1", "1", "2", "3", "2", "2", "3", "3"],
  8. "Value": [0.3, 1.2, 4.2, 5.1, 0.1, 0.2, 3.2, 4.1, 0.2]
  9. })
  10. colors = np.where(data["Value"] < THRESHOLD, "r", "#444444")
  11. seaborn.stripplot(
  12. data=data,
  13. x="Group",
  14. y="Value",
  15. color=colors
  16. )

经过编辑以提供完全可工作的示例。此示例中产生的错误是:"ValueError: 'c' argument has 9 elements, which is inconsistent with 'x' and 'y' with size 3."

英文:

I have a data frame I'm trying to plot as a stripplot using Seaborn. The data structure is:

Group Value
"1" 3.1
"2" 1.2
... ...

Where 'Group' are strings and 'Value' are floats.

I want to assign a color to any value less than a threshold value and I've tried assigning an array of colors for each point in the plot, but when I run this I get the error: "ValueError: 'c' argument has 37 elements, which is inconsistent with 'x' and 'y' with size 10"

I'm not sure how to troubleshoot this because I do not know where the size of 10 is coming from. the length of data["Group"] and data["Value"] is 37. The length of the unique values, i.e. len(set(data[&quot;Group&quot;])) is 4, so smaller than my colors list, but not 10.

The code I currently have is:

  1. import pandas as pd
  2. import numpy as np
  3. import seaborn
  4. from matplotlib import pyplot as plt
  5. THRESHOLD = 0.5
  6. data = pd.DataFrame({
  7. &quot;Group&quot;: [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;2&quot;,&quot;2&quot;,&quot;3&quot;,&quot;3&quot;],
  8. &quot;Value&quot;: [0.3, 1.2, 4.2, 5.1, 0.1, 0.2, 3.2, 4.1, 0.2]
  9. })
  10. colors = np.where(data[&quot;Value&quot;] &lt; THRESHOLD, &quot;r&quot;, &quot;#444444&quot;)
  11. seaborn.stripplot(
  12. data = data,
  13. x = &quot;Group&quot;,
  14. y = &quot;Value&quot;,
  15. color = colors
  16. )

Edited to provide a fully working example. The error produced in this example is: "ValueError: 'c' argument has 9 elements, which is inconsistent with 'x' and 'y' with size 3."

  1. ---------------------------------------------------------------------------
  2. ValueError Traceback (most recent call last)
  3. Cell In[7], line 11
  4. 4 data = pd.DataFrame({
  5. 5 &quot;Group&quot;: [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;2&quot;,&quot;2&quot;,&quot;3&quot;,&quot;3&quot;],
  6. 6 &quot;Value&quot;: [0.3, 1.2, 4.2, 5.1, 0.1, 0.2, 3.2, 4.1, 0.2]
  7. 7 })
  8. 9 colors = np.where(data[&quot;Value&quot;] &lt; THRESHOLD, &quot;r&quot;, &quot;#444444&quot;)
  9. ---&gt; 11 sns.stripplot(
  10. 12 data = data,
  11. 13 x = &quot;Group&quot;,
  12. 14 y = &quot;Value&quot;,
  13. 15 color = colors
  14. 16 )
  15. File ~\anaconda3\envs\py11\Lib\site-packages\seaborn\categorical.py:2537, in stripplot(data, x, y, hue, order, hue_order, jitter, dodge, orient, color, palette, size, edgecolor, linewidth, hue_norm, native_scale, formatter, legend, ax, **kwargs)
  16. 2529 size = kwargs.get(&quot;s&quot;, size)
  17. 2531 kwargs.update(dict(
  18. 2532 s=size ** 2,
  19. 2533 edgecolor=edgecolor,
  20. 2534 linewidth=linewidth)
  21. 2535 )
  22. -&gt; 2537 p.plot_strips(
  23. 2538 jitter=jitter,
  24. 2539 dodge=dodge,
  25. 2540 color=color,
  26. 2541 edgecolor=edgecolor,
  27. 2542 plot_kws=kwargs,
  28. 2543 )
  29. 2545 # XXX this happens inside a plotting method in the distribution plots
  30. 2546 # but maybe it&#39;s better out here? Alternatively, we have an open issue
  31. 2547 # suggesting that _attach could add default axes labels, which seems smart.
  32. 2548 p._add_axis_labels(ax)
  33. File ~\anaconda3\envs\py11\Lib\site-packages\seaborn\categorical.py:299, in _CategoricalPlotterNew.plot_strips(self, jitter, dodge, color, edgecolor, plot_kws)
  34. 296 sub_data[var] = np.power(10, sub_data[var])
  35. 298 ax = self._get_axes(sub_vars)
  36. --&gt; 299 points = ax.scatter(sub_data[&quot;x&quot;], sub_data[&quot;y&quot;], color=color, **plot_kws)
  37. 301 if &quot;hue&quot; in self.variables:
  38. 302 points.set_facecolors(self._hue_map(sub_data[&quot;hue&quot;]))
  39. File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.&lt;locals&gt;.inner(ax, data, *args, **kwargs)
  40. 1439 @functools.wraps(func)
  41. 1440 def inner(ax, *args, data=None, **kwargs):
  42. 1441 if data is None:
  43. -&gt; 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
  44. 1444 bound = new_sig.bind(ax, *args, **kwargs)
  45. 1445 auto_label = (bound.arguments.get(label_namer)
  46. 1446 or bound.kwargs.get(label_namer))
  47. File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\axes\_axes.py:4602, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
  48. 4599 if edgecolors is None:
  49. 4600 orig_edgecolor = kwargs.get(&#39;edgecolor&#39;, None)
  50. 4601 c, colors, edgecolors = \
  51. -&gt; 4602 self._parse_scatter_color_args(
  52. 4603 c, edgecolors, kwargs, x.size,
  53. 4604 get_next_color_func=self._get_patches_for_fill.get_next_color)
  54. 4606 if plotnonfinite and colors is None:
  55. 4607 c = np.ma.masked_invalid(c)
  56. File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\axes\_axes.py:4455, in Axes._parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func)
  57. 4451 else:
  58. 4452 if len(colors) not in (0, 1, xsize):
  59. 4453 # NB: remember that a single color is also acceptable.
  60. 4454 # Besides *colors* will be an empty array if c == &#39;none&#39;.
  61. -&gt; 4455 raise invalid_shape_exception(len(colors), xsize)
  62. 4456 else:
  63. 4457 colors = None # use cmap, norm after collection is created
  64. ValueError: &#39;c&#39; argument has 9 elements, which is inconsistent with &#39;x&#39; and &#39;y&#39; with size 3.

答案1

得分: 0

You should use hue instead of color to mark the two groups, and palette to assign the desired colors.

  1. import seaborn as sns
  2. import pandas as pd
  3. import numpy as np
  4. df = {'Value': np.random.randn(10),
  5. 'Group': np.random.randint(0, 10, size=(10,))}
  6. data = pd.DataFrame(df)
  7. THRESHOLD = 0.1
  8. colors = np.where(data["Value"] < THRESHOLD, "less than threshold", "Bigger than threshold")
  9. sns.stripplot(
  10. data=data,
  11. x="Group",
  12. y="Value",
  13. hue=colors,
  14. palette=['red', 'blue']
  15. )
英文:

You should use hue instead of color to mark the two groups, and palette to assign the desired colors.

  1. import seaborn as sns
  2. import pandas as pd
  3. import numpy as np
  4. df = {&#39;Value&#39;: np.random.randn(10),
  5. &#39;Group&#39;: np.random.randint(0, 10, size=(10,))}
  6. data = pd.DataFrame(df)
  7. THRESHOLD = 0.1
  8. colors = np.where(data[&quot;Value&quot;] &lt; THRESHOLD, &quot;less than threshold&quot;, &quot;Bigger than threshold&quot;)
  9. sns.stripplot(
  10. data = data,
  11. x = &quot;Group&quot;,
  12. y = &quot;Value&quot;,
  13. hue = colors,
  14. palette=[&#39;red&#39;, &#39;blue&#39;]
  15. )

huangapple
  • 本文由 发表于 2023年5月10日 23:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定