Plotnine 图例左对齐
我无法把图例放到左边,尽管我已经加了 legend_box_just="left"
。我用的是 Plotnine 版本 0.13.0 和 Python 3.11。
代码:
df = pd.DataFrame({
'Date': pd.date_range(start="2024-01-01", periods=11, freq="W").repeat(3),
'Variable': ['A', 'B', 'C'] * 11,
'Value': np.random.choice(range(50), 33)
})
plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
+ geom_bar(stat="identity")
+ labs(title="Title")
+ theme_minimal()
+ theme(
legend_title=element_blank(),
legend_direction="horizontal", legend_box="horizontal",
legend_position="top", legend_box_just="left")
)
plot.show()
我该怎么做才能让说明文字靠左对齐,并和标题对齐呢?
2 个回答
1
如果你想把图例放在左上角,我建议你给图例的位置传入坐标。
举个例子:
plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
+ geom_bar(stat="identity")
+ labs(title="Title")
+ theme_minimal()
+ theme(
legend_title=element_blank(),
legend_direction="horizontal", legend_box="horizontal",
legend_position=(0.2,0.9), legend_box_just="left")
)
这是一个图:
1
使用 legend_justification=0
或者 legend_justification_top=0
。
import pandas as pd
import numpy as np
from plotnine import *
df = pd.DataFrame({
'Date': pd.date_range(start="2024-01-01", periods=11, freq="W").repeat(3),
'Variable': ['A', 'B', 'C'] * 11,
'Value': np.random.choice(range(50), 33)
})
plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
+ geom_bar(stat="identity")
+ labs(title="Title")
+ theme_minimal()
+ theme(
legend_justification=0,
# legend_justification_top=0, # Alternatively, to be more specific
legend_title=element_blank(),
legend_direction="horizontal",
legend_box="horizontal",
legend_position="top",
legend_box_just="left"
)
)
plot.show()
这暴露了一个问题,也就是空白的图例标题被算进了对齐的计算里。与此同时,你可以使用一个负的对齐因子。很快会有修复版本发布。