英文:
How to specify `scale_color_manual()` in `python`, using `lets-plot`
问题
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
data = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg2.csv')
ggplot(data, aes(x="engine horsepower", y="miles per gallon")) + geom_point(aes(color="origin of car"))
In R
, using ggplot2
, I would manually set the colors by writing:
... + scale_color_manual(values = c("US" = "red", "Asia" = "green", "Europe" = "blue")
How can I do the same in Python
with lets-plot
?
<details>
<summary>英文:</summary>
My code is:
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
data = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg2.csv')
ggplot(data, aes(x="engine horsepower", y="miles per gallon")) + geom_point(aes(color="origin of car"))
And the output is:
[![enter image description here](https://i.stack.imgur.com/8D6qN.png)](https://i.stack.imgur.com/8D6qN.png)
In `R`, using `ggplot2`, I would manually set the colors by writing:
... + scale_color_manual(values = c("US" = "red", "Asia" = "green", "Europe" = "blue")
How can I do the same in `Python` with `lets-plot`?
`lets-plot` reference manual for this function doesn't seem to help: [here](https://lets-plot.org/pages/api/lets_plot.scale_color_manual.html?highlight=scale_color_manual#lets_plot.scale_color_manual)
</details>
# 答案1
**得分**: 2
以下是您要翻译的内容:
基本上,`lets-plot` 中的操作与 R 类似。使用 pandas Series,您可以创建类似 R 中的命名向量:
```python
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
data = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg2.csv')
ggplot(data, aes(x="engine horsepower", y="miles per gallon")) + \
geom_point(aes(color="origin of car")) + \
scale_color_manual(values=pd.Series(["red", "green", "blue"],
index=['US', 'Asia', 'Europe']))
英文:
Basically it's the same in lets-plot
. Using a pandas Series you could create a named vector similar to R:
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
data = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg2.csv')
ggplot(data, aes(x="engine horsepower", y="miles per gallon")) + \
geom_point(aes(color="origin of car")) + \
scale_color_manual(values = pd.Series(["red", "green", "blue"],
index=['US', 'Asia', 'Europe']))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论