How do I create a log(x) graph using xlsxwriter in python?

Viewed 715

I am trying to create a log(x) graph in xksxwriter, I am using " chart1.set_x_axis({'log_base' : 10})" to set the x axis as a logarithmic axis. However the graph still appears linear on both axes.

Here is the portion where I am setting the graph properties

chart1.set_x_axis({'log_base': 10})
chart1.set_x_axis({'min': 1000, 'max': 100000})
chart1.set_x_axis({'interval_tick': 100})
chart1.set_x_axis({'name': 'x axis'})

chart1.set_y_axis({'min': 0, 'max': 180})
chart1.set_y_axis({'name': 'y axis'})
chart1.set_size({'width': 1192, 'height': 729})
chart1.set_title({'name': 'log(x) vs. y'})
worksheet2.insert_chart('A1', chart1)

I expect the graph to appear logarithmic but it still appears linear.

2 Answers

Here is an example that demonstrates that the log axis works with XlsxWriter charts:

import xlsxwriter

workbook = xlsxwriter.Workbook('log_demo.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write_column('A1', [1, 10, 100, 1000])

chart = workbook.add_chart({'type': 'line'})
chart.add_series({'values': '=Sheet1!$A$1:$A$4'})
chart.set_y_axis({'log_base': 10})

worksheet.insert_chart('C2', chart)

workbook.close()

Output:

enter image description here

As you can see the Y axis is clearly log scale.

However, there is an Excel gotcha here. The X-axes for most chart types (apart from Scatter) are called Category axes. They can have numeric values but they aren't numeric, they are generally just category names. This type of axis doesn't support log scaling (or a lot of other features). See the Chart Value and Category Axes section of the XlsxWriter docs for more details.

If you want a log X-axis you will probably have to use a Scatter type chart.

Update:

There is also an issue with your code. XlsxWriter requires that all axis properties are set in one go, instead of multiptle calls to set_x_axis(). Like this:

chart1.set_x_axis({'log_base': 10,
                   'min': 1000, 
                   'max': 100000,
                   'interval_tick': 100,
                   'name': 'x axis'})

It turns out the set_x_axis lines must be reordered as such:

chart1.set_x_axis({'min': 1000, 'max': 100000})
chart1.set_x_axis({'interval_tick': 100})
chart1.set_x_axis({'log_base': 10})
chart1.set_x_axis({'name': 'x axis'})

chart1.set_y_axis({'min': 0, 'max': 180})
chart1.set_y_axis({'name': 'y axis'})
chart1.set_size({'width': 1192, 'height': 729})
chart1.set_title({'name': 'log(x) vs. y'})
worksheet2.insert_chart('A1', chart1)
Related