如何在python pptx中为图表添加边框

时间:2017-06-27 18:06:29

标签: python-3.x python-pptx

我有一个堆积条形图,我想在图表周围放置一个边框,但图表没有'line'属性:

    from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_TICK_MARK, XL_LABEL_POSITION, XL_LEGEND_POSITION
from pptx.dml.color import RGBColor
from pptx.util import Inches, Pt

# define chart data 
chart_data = ChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
chart_data.add_series('Series 2', (10.2, 11.4, 6.7))
chart_data.add_series('Series 3', (2.2, 8.4, 1.7))



# add chart to slide
x, y, cx, cy = Inches(1), Inches(1), Inches(5), Inches(3.5)
ThisChart = ThisSlide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_STACKED, x, y, cx, cy, chart_data
).chart # the '.chart' is getting the chart object from the chart creation


#Put a border around the chart *This is the part that not working *
ThisBorder = ThisChart.line # <--- there is no line attribute
ThisBorder.color.rgb = RGBColor(0xFF, 0x00, 0x00) # hex
ThisBorder.width = inches(0.1)

#Give the chart a title
ThisChart.chart_title.has_text_frame = True
ThisChart.chart_title.text_frame.text = "My Chart Title"

# Give the chart a legend
ThisChart.has_legend = True
ThisChart.legend.position = XL_LEGEND_POSITION.RIGHT
ThisChart.legend.include_in_layout = False
ThisChart.legend.font.size = Pt(11)

#add data labels
plot = ThisChart.plots[0] # The first Series
plot.has_data_labels = True # display the value on the bar
plot.overlap = 100 # make the bars stacked
data_labels = plot.data_labels
data_labels.font.size = Pt(11)
data_labels.font.color.rgb = RGBColor(0,0,0)
data_labels.number_format = "#,##0"


ThisChart.value_axis.has_minor_gridlines = False
ThisChart.value_axis.has_major_gridlines = False
ThisChart.value_axis.tick_labels.font.size = Pt(12)
ThisChart.value_axis.tick_labels.number_format = "#,##0"
ThisChart.category_axis.tick_labels.font.size = Pt(12)

# Colour the bars, I'm not going to really use these colours, just getting things working :)
ThisChart.series[0].fill.solid()
ThisChart.series[0].fill.fore_color.rgb = RGBColor(244,66,152) # Pink hex: F44298, RGB: 244,66,152
ThisChart.series[1].fill.solid()
ThisChart.series[1].fill.fore_color.rgb = RGBColor(66,134,244) # Blue hex: 4286F4, RGB: 66,134,244
ThisChart.series[2].fill.solid()
ThisChart.series[2].fill.fore_color.rgb = RGBColor(92,244,66) # Green hex: 5CF442, RGB: 92,244,66

还有另一种方法可以使图表区域有边框吗?只是在包含图例的图表区域周围寻找一个薄的黑色边框。我打算在幻灯片上有四张图表。

1 个答案:

答案 0 :(得分:0)

此功能尚未在python-pptx中实施。如果是,则为Chart.plot_area.format.line,以防您想在GitHub存储库上添加功能请求。

与此同时,你有两个选择,如果包括“make do without”,则有三个选择:)

第一种是在“开始”或“模板”演示文稿中包含以您希望的方式格式化的图表,并使用Chart.replace_data()方法仅更改其描绘的数据。这为您提供了非常广泛的控制,但它要求您事先知道您想要多少图表以及在哪里。

第二种方法是使用lxml级别调用来操作底层XML以添加所需元素并适当地设置属性。如果您搜索“python-pptx变通办法函数”,可以找到有关此方法的更多信息。