Learn R Programming

xlcharts

xlcharts, an R interface to OpenPyXL to create native Excel charts and work with Microsoft Excel files.

Introduction

xlcharts was born from the lack of existing R packages to create native Excel charts and make advanced customization on Microsoft Excel files.

It is an R wrapper for the OpenPyXL Python library using the reticulate R package under the hood. The xlcharts documentation is a partial replica of the OpenPyXL documentation, where Python code is replaced by R code (when possible).

All kudos goes to Eric Gazoni, Charlie Clark and other authors for developing the OpenPyXL Python library.

FULL DOCUMENTATION AT www.felixluginbuhl.com/xlcharts

Installation

Install xlcharts

install.packages("xlcharts")

# development version from GitHub:
#devtools::install_github("lgnbhl/xlcharts")

Install Miniconda

If Miniconda is not install on your machine, an R prompt should ask you if you want to install it after loading the xlcharts R package. Type “Y” for “yes”.

library(xlcharts)
Would you like to install Miniconda? [Y/n]:

You can also install Miniconda using the reticulate R package.

reticulate::install_miniconda()

Install OpenPyXL Python library

Then you have to install the OpenPyXL Python library.

xlcharts::install_openpyxl()

You can also specify a desired location for Python before interacting with the functions of the R package.

#reticulate::use_virtualenv("~/pythonenvs/userenv")

Create a workbook

To prevent potential formatting issue, we will always load data from an existing Excel file.

If you have a dataframe in R, you can simply write it as an Excel file using the write_xlsx() function imported from the writexl R package.

library(xlcharts)

treeData <- data.frame(
  "Type" = c("Maple", "Oak", "Pine"), 
  "LeafColor" = c("Red", "Green", "Green"), 
  "Height" = c(549, 783, 1204)
  )

write_xlsx(x = treeData, path = "treeData.xlsx")

Then you can load the Excel workbook in R using load_workbook().

wb <- load_workbook(filename = "treeData.xlsx")

Let’s get the active worksheet of our workbook.

ws <- wb |> active()

Access cells

You can access and modify cells using double brackets or cell():

ws[["C2"]]$value <- 550
#ws$cell(row = 2, column = 3, value = 550) # also works

ws[["C2"]]$value
[1] 550

Ranges of cells can be accessed using slicing:

colC <- ws[["C"]]
col_range = ws[["C:D"]]
row10 <- ws[[10]]

Get the dimensions:

ws$dimensions
[1] "A1:C4"

Make a bar chart

We need to add references to where the data and categories are in the worksheet.

data <- Reference(ws, min_col = 3, min_row = 2, max_row = 4, max_col = 3)
categories <- Reference(ws, min_col = 1, min_row = 2, max_row = 4, max_col = 1)

Now we can construct the skeleton of what will be our bar chart.

chart <- BarChart(
  type = "bar",
  title = "Tree Height",
  legend = NULL
) |>
  x_axis(title = "Height (cm)") |>
  y_axis(title = "Tree Type")

And pass the data and categories to the chart object.

chart |>
  add_data(data = data) |>
  set_categories(labels = categories)

We can add the chart to the worksheet.

ws |> add_chart(chart, anchor =  "E1")

And finally save the workbook as an Excel file.

wb |> save_workbook("TreeData.xlsx")

For advanced users

The xlcharts R functions give access to OpenPyXL Python classes.

Properties and methods can be accessed using the $ sign on any object, for example:

wb <- Workbook()
ws <- wb$active
wb$save(filename = "empty.xlsx")

The OpenPyXL Python related documentation URL is provided in every R function documentation, where all arguments/parameters are described in more details. Documentation can be accessed using the ? sign, for example:

?Workbook()

The xlcharts R package also provides additional R functions (not calling an OpenPyXL Python class) as helpers, to make the R code easier to read and write:

  • active()
  • x_axis()
  • y_axis()
  • set_catagories()
  • add_data()
  • add_table()
  • add_chart()

It also provides functions imported from other Python modules:

  • iadd() from the operator Python module.
  • deepcopy() from the copy Python module.

Important differences between Python and R:

  • lists start at 0 with Python, but at 1 with R.
  • instead of single brackets ([]) in Python, use double brackets ([[]]) with R.

Always keep in mind that Python array indices are zero-based, while R indices are 1-based.

Numbers used in arguments/parameters should be integers (use L after the number in R), for example 1L, to be correctly evaluated by the OpenPyXL Python library.

Unfortunately some OpenPyXL Python classes from different module have similar names. An arbitrary choice has been made to import some from a specific module instead of another. Maybe a condition will be added in a future version of the package (any contribution is very welcomed!). In the meantime, you can access any class as such:

openpyxl <- reticulate::import("openpyxl")
openpyxl$[OpenPyXL Python class]

Contribute

Any contribution is very welcomed!

If you find this R package helpful, feel free to mention it on social media. You can follow me on LinkedIn for R package updates: Felix Luginbuhl.

Copy Link

Version

Install

install.packages('xlcharts')

Monthly Downloads

532

Version

0.0.1

License

MIT + file LICENSE

Last Published

April 18th, 2024

Functions in xlcharts (0.0.1)

AdjustHandleList

AdjustHandleList
Blip

Blip
Backdrop

Backdrop
AxDataSource

AxDataSource
AlphaFloorEffect

AlphaFloorEffect
BarChart3D

BarChart3D
BarChart

BarChart
BlipFillProperties

BlipFillProperties
BubbleChart

BubbleChart
CalcProperties

CalcProperties
AlphaInverseEffect

AlphaInverseEffect
Border

Border
AutoFilter

AutoFilter
ArrayDescriptor

ArrayDescriptor
Chartsheet

Chartsheet
AreaChart3D

AreaChart3D
AdjPoint2D

AdjPoint2D
Alignment

Alignment
BandFormatList

BandFormatList
AutonumberBullet

AutonumberBullet
AnchorClientData

AnchorClientData
AlphaReplaceEffect

AlphaReplaceEffect
BlurEffect

BlurEffect
BookView

BookView
ChartRelation

ChartRelation
BandFormat

BandFormat
CellIsRule

CellIsRule
Camera

Camera
ColorFilter

ColorFilter
CellRange

CellRange
ChartsheetProperties

ChartsheetProperties
DashStop

DashStop
ChartContainer

ChartContainer
ColorMapping

ColorMapping
ColorChoice

ColorChoice
ColorChangeEffect

ColorChangeEffect
ChartLines

ChartLines
Connection

Connection
Bevel

Bevel
CellSmartTags

CellSmartTags
BiLevelEffect

BiLevelEffect
CellSmartTagPr

CellSmartTagPr
DashStopList

DashStopList
ChartsheetProtection

ChartsheetProtection
ChartsheetView

ChartsheetView
ConnectionSite

ConnectionSite
CellSmartTag

CellSmartTag
DataBarRule

DataBarRule
ConditionalFormatting

ConditionalFormatting
Break

Break
ChartSpace

ChartSpace
EmptyCell

EmptyCell
ConditionalFormattingList

ConditionalFormattingList
ChartsheetViewList

ChartsheetViewList
Dimension

Dimension
DataLabel

DataLabel
CellStyle

CellStyle
Comment

Comment
ColBreak

ColBreak
Cell

Cell
EffectList

EffectList
DataBar

DataBar
DataLabelList

DataLabelList
DimensionHolder

DimensionHolder
ExcelReader

ExcelReader
DataPoint

DataPoint
DuotoneEffect

DuotoneEffect
ColumnDimension

ColumnDimension
CellWatch

CellWatch
DynamicFilter

DynamicFilter
CellStyleList

CellStyleList
CellWatches

CellWatches
Extension

Extension
ExternalCell

ExternalCell
EMU_to_cm

EMU_to_cm
ColorList

ColorList
EffectContainer

EffectContainer
Control

Control
CharacterProperties

CharacterProperties
EMU_to_inch

EMU_to_inch
ExtensionList

ExtensionList
ExcelWriter

ExcelWriter
ExternalBook

ExternalBook
Legend

Legend
Fill

Fill
CommentSheet

CommentSheet
ConnectionSiteList

ConnectionSiteList
CommentRecord

CommentRecord
FillOverlayEffect

FillOverlayEffect
ExternalData

ExternalData
FilterColumn

FilterColumn
ExternalDefinedName

ExternalDefinedName
FormatObject

FormatObject
FormulaRule

FormulaRule
Level

Level
ColRange

ColRange
FunctionGroupList

FunctionGroupList
FunctionGroup

FunctionGroup
ExternalSheetNames

ExternalSheetNames
ControlProperty

ControlProperty
CustomFilters

CustomFilters
LightRig

LightRig
IgnoredErrors

IgnoredErrors
Hyperlink

Hyperlink
HeaderFooterItem

HeaderFooterItem
Filters

Filters
Controls

Controls
HyperlinkList

HyperlinkList
IconSet

IconSet
DataValidation

DataValidation
ColorReplaceEffect

ColorReplaceEffect
ExternalReference

ExternalReference
GraphicFrameLocking

GraphicFrameLocking
GraphicObject

GraphicObject
Color

Color
Paragraph

Paragraph
CustomSplit

CustomSplit
ColorScale

ColorScale
SchemeColor

SchemeColor
CustomFilter

CustomFilter
CustomGeometry2D

CustomGeometry2D
DocumentProperties

DocumentProperties
MergeCells

MergeCells
ColorScaleRule

ColorScaleRule
ErrorBars

ErrorBars
InlineFont

InlineFont
DataTable

DataTable
ConnectorLocking

ConnectorLocking
DefinedName

DefinedName
IgnoredError

IgnoredError
DefinedNameList

DefinedNameList
GradientFill

GradientFill
DataValidationList

DataValidationList
IconSetRule

IconSetRule
NamedStyle

NamedStyle
Path2DList

Path2DList
WriteOnlyCell

WriteOnlyCell
DocumentSecurity

DocumentSecurity
DrawingHF

DrawingHF
EMU_to_pixels

EMU_to_pixels
DummyWorksheet

DummyWorksheet
LineChart3D

LineChart3D
DisplayUnitsLabel

DisplayUnitsLabel
DataTableFormula

DataTableFormula
DisplayUnitsLabelList

DisplayUnitsLabelList
MergedCellRange

MergedCellRange
GeomGuide

GeomGuide
NamedStyleList

NamedStyleList
DoughnutChart

DoughnutChart
NumDataSource

NumDataSource
LineEndProperties

LineEndProperties
Drawing

Drawing
LegendEntry

LegendEntry
Outline

Outline
CustomProperties

CustomProperties
LineBreak

LineBreak
PlotArea

PlotArea
PhoneticProperties

PhoneticProperties
CustomProperty

CustomProperty
DateAxis

DateAxis
PrintTitles

PrintTitles
NestedOverlap

NestedOverlap
MultiCellRange

MultiCellRange
MultiLevelStrData

MultiLevelStrData
ObjectAnchor

ObjectAnchor
RelativeRect

RelativeRect
GradientFillProperties

GradientFillProperties
NestedGapAmount

NestedGapAmount
deepcopy

Deep copy operation from deepcopy Python module
Reference

Reference
PresetShadowEffect

PresetShadowEffect
OneCellAnchor

OneCellAnchor
EmbeddedWAVAudioFile

EmbeddedWAVAudioFile
NonVisualConnectorProperties

NonVisualConnectorProperties
ExternalSheetDataSet

ExternalSheetDataSet
HSLEffect

HSLEffect
GeomRect

GeomRect
TableStyleList

TableStyleList
MultiLevelStrRef

MultiLevelStrRef
DateGroupItem

DateGroupItem
ProjectedPieChart

ProjectedPieChart
XDRTransform2D

XDRTransform2D
NonVisualGraphicFrameProperties

NonVisualGraphicFrameProperties
ExternalLink

ExternalLink
NonVisualPictureProperties

NonVisualPictureProperties
PageBreak

PageBreak
PathShadeProperties

PathShadeProperties
GeomGuideList

GeomGuideList
LinearShadeProperties

LinearShadeProperties
PrintOptions

PrintOptions
FileVersion

FileVersion
column_index_from_string

column_index_from_string
PhoneticText

PhoneticText
DifferentialStyle

DifferentialStyle
Layout

Layout
DifferentialStyleList

DifferentialStyleList
ReadOnlyCell

ReadOnlyCell
PageMargins

PageMargins
Spacing

Spacing
PresetGeometry2D

PresetGeometry2D
InnerShadowEffect

InnerShadowEffect
ShapeStyle

ShapeStyle
GroupShapeProperties

GroupShapeProperties
WebPublishItem

WebPublishItem
Vector3D

Vector3D
WebPublishObject

WebPublishObject
RuleType

RuleType
Scaling

Scaling
RowBreak

RowBreak
GraphicData

GraphicData
GradientStop

GradientStop
FileSharing

FileSharing
GraphicalProperties

GraphicalProperties
Font

Font
Point3D

Point3D
Side

Side
XDRPositiveSize2D

XDRPositiveSize2D
LuminanceEffect

LuminanceEffect
HeaderFooter

HeaderFooter
SheetBackgroundPicture

SheetBackgroundPicture
PositiveSize2D

PositiveSize2D
FontReference

FontReference
XDRPoint2D

XDRPoint2D
GroupLocking

GroupLocking
Path2D

Path2D
IconFilter

IconFilter
GlowEffect

GlowEffect
NumData

NumData
StretchInfoProperties

StretchInfoProperties
cast_percentage

cast_percentage
RowDimension

RowDimension
ListStyle

ListStyle
StrVal

StrVal
GrayscaleEffect

GrayscaleEffect
GroupTransform2D

GroupTransform2D
SortState

SortState
MergeCell

MergeCell
LineProperties

LineProperties
NumFmt

NumFmt
NumericAxis

NumericAxis
HSLColor

HSLColor
Selection

Selection
ParagraphProperties

ParagraphProperties
SphereCoords

SphereCoords
Table

Table
SortCondition

SortCondition
TablePartList

TablePartList
Title

Title
MergedCell

MergedCell
SmartTags

SmartTags
TextAxis

TextAxis
ManualLayout

ManualLayout
Related

Related
PrintSettings

PrintSettings
InputCells

InputCells
PrintArea

PrintArea
LineChart

LineChart
Image

Image
PageSetupProperties

PageSetupProperties
SheetViewList

SheetViewList
PivotSource

PivotSource
Transform2D

Transform2D
absolute_coordinate

absolute_coordinate
cm_to_dxa

cm_to_dxa
SheetProtection

SheetProtection
NonVisualDrawingShapeProps

NonVisualDrawingShapeProps
SheetFormatProperties

SheetFormatProperties
SurfaceChart3D

SurfaceChart3D
SmartTag

SmartTag
NumRef

NumRef
Pane

Pane
PrintPageSetup

PrintPageSetup
PivotFormat

PivotFormat
TableColumn

TableColumn
Scene3D

Scene3D
ScenarioList

ScenarioList
get_type

get_type
Shape

Shape
Stylesheet

Stylesheet
XMLColumnProps

XMLColumnProps
SpreadsheetDrawing

SpreadsheetDrawing
StyleArray

StyleArray
active

active
add_chart

Add a chart to the sheet
Rule

Rule
Marker

Marker
y_axis

y_axis
pixels_to_points

pixels_to_points
pixels_to_EMU

pixels_to_EMU
RegularTextRun

RegularTextRun
save_workbook

save_workbook
SystemColor

SystemColor
NumVal

NumVal
TableNameDescriptor

TableNameDescriptor
PatternFillProperties

PatternFillProperties
PatternFill

PatternFill
StopList

StopList
Shape3D

Shape3D
SmartTagList

SmartTagList
RichTextProperties

RichTextProperties
Stop

Stop
Trendline

Trendline
ValueDescriptor

ValueDescriptor
ScatterChart

ScatterChart
SoftEdgesEffect

SoftEdgesEffect
RowRange

RowRange
Point2D

Point2D
Protection

Protection
StockChart

StockChart
TableFormula

TableFormula
SeriesFactory

SeriesFactory
SeriesLabel

SeriesLabel
PieChart3D

PieChart3D
PieChart

PieChart
add_table

Check for duplicate name in definedNames and other worksheet tables before adding table.
TableStyleElement

TableStyleElement
Series

Series
WebPublishing

WebPublishing
SeriesAxis

SeriesAxis
TintEffect

TintEffect
SheetDimension

SheetDimension
Workbook

Workbook
RadarChart

RadarChart
WorkbookParser

WorkbookParser
TextNormalAutofit

TextNormalAutofit
avoid_duplicate_name

avoid_duplicate_name
WebPublishObjectList

WebPublishObjectList
inch_to_dxa

inch_to_dxa
Scenario

Scenario
StyleMatrixReference

StyleMatrixReference
WorkbookProperties

WorkbookProperties
StrData

StrData
angle_to_degrees

angle_to_degrees
builtin_format_code

builtin_format_code
degrees_to_angle

degrees_to_angle
hash_password

hash_password
write_xlsx

Export to xlsx
TitleDescriptor

TitleDescriptor
SurfaceChart

SurfaceChart
x_axis

x_axis
cast_numeric

cast_numeric
install_openpyxl

Install openpyxl Python module
rows_from_range

rows_from_range
TableStyle

TableStyle
SolidColorFillProperties

SolidColorFillProperties
SheetView

SheetView
title_maker

title_maker
cast_time

cast_time
SmartTagProperties

SmartTagProperties
TableStyleInfo

TableStyleInfo
TrendlineLabel

TrendlineLabel
StrRef

StrRef
set_categories

set_categories
WorksheetProperties

WorksheetProperties
TwoCellAnchor

TwoCellAnchor
dxa_to_cm

dxa_to_cm
builtin_format_id

builtin_format_id
add_data

Add a range of data in a single pass.
UpDownBars

UpDownBars
iadd

iadd from operator Python module
XYSeries

XYSeries
points_to_pixels

points_to_pixels
cm_to_EMU

cm_to_EMU
TextField

TextField
TextBlock

TextBlock
get_column_letter

get_column_letter
inch_to_EMU

inch_to_EMU
quote_sheetname

quote_sheetname
WorkbookProtection

WorkbookProtection
WorksheetCopy

WorksheetCopy
coordinate_from_string

coordinate_from_string
get_column_interval

get_column_interval
write_stylesheet

write_stylesheet
install_pillow

Install pillow Python module
expand_cell_ranges

expand_cell_ranges
range_boundaries

range_boundaries
coordinate_to_tuple

coordinate_to_tuple
load_workbook

load_workbook
range_to_tuple

range_to_tuple
short_color

short_color
AbsoluteAnchor

AbsoluteAnchor
AlphaBiLevelEffect

AlphaBiLevelEffect
AlphaModulateEffect

AlphaModulateEffect
AnchorMarker

AnchorMarker
AlphaCeilingEffect

AlphaCeilingEffect
AlphaModulateFixedEffect

AlphaModulateFixedEffect
AreaChart

AreaChart
ArrayFormula

ArrayFormula
AuthorList

AuthorList