Chart With Secondary Y-axis And X-axis As Dates
I'm trying to create a chart in openpyxl with a secondary y-axis and an DateAxis for the x-values. For this MWE, I've adapted the secondary axis example with the DateAxis example.
Solution 1:
So, as noted in my comments, there isn't really much benefit in DateAxes
but if you use them then they have a default id of 500. This is important because it is the value that the y-axes need to cross. CrossAx
for the category/date axis doesn't seen to matter. The following works for me:
from datetime import datetime
from openpyxl import Workbook, chart
wb = Workbook()
ws = wb.active
xvals = ['date', *[datetime(2018, 11, d, d+12) for d in range(1, 7)]]
avals = ['aliens', 6, 3, 4, 3, 6, 7]
hvals = ['humans', 10, 40, 50, 20, 10, 50]
for row in zip(xvals, avals, hvals):
ws.append(row)
dates = chart.Reference(ws, min_row=2, max_row=7, min_col=1, max_col=1)
aliens = chart.Reference(ws, min_row=1, max_row=7, min_col=2, max_col=2)
humans = chart.Reference(ws, min_row=1, max_row=7, min_col=3, max_col=3)
c1 = chart.LineChart()
c1.x_axis = chart.axis.DateAxis() # axId defaults to 500
c1.x_axis.title = "Date"
c1.x_axis.crosses = "min"
c1.x_axis.majorTickMark = "out"
c1.x_axis.number_format = "yyyy-mmm-dd"
c1.add_data(aliens, titles_from_data=True)
c1.set_categories(dates)
c1.y_axis.title = 'Aliens'
c1.y_axis.crossAx = 500
c1.y_axis.majorGridlines = None
# Create a second chart
c2 = chart.LineChart()
c2.x_axis.axId = 500 # same as c1
c2.x_axis.crosses = "min"
c2.add_data(humans, titles_from_data=True)
c2.set_categories(dates)
c2.y_axis.axId = 20
c2.y_axis.title = "Humans"
c2.y_axis.crossAx = 500
# Display y-axis of the second chart on the right
# by setting it to cross the x-axis at its maximum
c1.y_axis.crosses = "max"
c1 += c2
ws.add_chart(c1, "E4")
wb.save("secondary.xlsx")
Post a Comment for "Chart With Secondary Y-axis And X-axis As Dates"