Skip to main content
 首页 » 编程设计

python之在用于 Python 的 ggplot 中,将离散 X 标度与 geom_point() 一起使用

2025年04月02日8落叶无声

以下示例返回错误。似乎不支持在 Python 的 ggplot 中对 x 轴使用离散(非连续)刻度?

import pandas as pd 
import ggplot 
 
df = pd.DataFrame.from_dict({'a':['a','b','c'], 
                   'percentage':[.1,.2,.3]}) 
 
p = ggplot.ggplot(data=df, 
                  aesthetics=ggplot.aes(x='a', 
                                        y='percentage'))\ 
    + ggplot.geom_point() 
 
print(p) 

如前所述,这将返回:

Traceback (most recent call last): 
  File "/Users/me/Library/Preferences/PyCharm2016.1/scratches/scratch_1.py", line 30, in <module> 
    print(p) 
  File "/Users/me/lib/python3.5/site-packages/ggplot/ggplot.py", line 116, in __repr__ 
    self.make() 
  File "/Users/me/lib/python3.5/site-packages/ggplot/ggplot.py", line 627, in make 
    layer.plot(ax, facetgroup, self._aes, **kwargs) 
  File "/Users/me/lib/python3.5/site-packages/ggplot/geoms/geom_point.py", line 60, in plot 
    ax.scatter(x, y, **params) 
  File "/Users/me/lib/python3.5/site-packages/matplotlib/__init__.py", line 1819, in inner 
    return func(ax, *args, **kwargs) 
  File "/Users/me/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 3838, in scatter 
    x, y, s, c = cbook.delete_masked_points(x, y, s, c) 
  File "/Users/me/lib/python3.5/site-packages/matplotlib/cbook.py", line 1848, in delete_masked_points 
    raise ValueError("First argument must be a sequence") 
ValueError: First argument must be a sequence 

在离散尺度上使用 ggplot 散点有任何解决方法吗?

请您参考如下方法:

一种选择是生成连续序列,并使用原始变量作为标签。但这似乎是一个痛苦的解决方法。

df = pd.DataFrame.from_dict( {'a':[0,1,2], 
                   'a_name':['a','b','c'], 
                   'percentage':[.1,.2,.3]}) 
 
p = ggplot.ggplot(data=df, 
                  aesthetics=ggplot.aes(x='a', 
                                        y='percentage'))\ 
    + ggplot.geom_point()\ 
    + ggplot.scale_x_continuous(breaks=list(df['a']), 
                              labels=list(df['a_name']))