GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing plotly.com — Axes in Python This tutorial explains how to set the properties of 2-dimensional Cartesian axes, namely Other kinds of subplots and axes are described in other tutorials:
See also the tutorials on facet plots, subplots and multiple axes. 2-D Cartesian Axis Types and Auto-Detection¶The different types of Cartesian axes are configured via the
The axis type is auto-detected by looking at data from the first trace linked to this axis:
Forcing an axis to be categorical¶It is possible to force the axis type by setting explicitly In [1]:
import plotly.express as px fig = px.bar(x=["a", "a", "b", 3], y = [1,2,3,4]) fig.update_xaxes(type='category') fig.show() General Axis properties¶The different groups of Cartesian axes properties are
The examples on this page apply to axes of any type, but extra attributes are available for axes of type Set and Style Axes Title Labels¶Set axis title text with Plotly Express¶Axis titles are automatically set to the column names when using Plotly Express with a data frame as input. In [2]:
import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", color="sex") fig.show() Axis titles (and legend titles) can also be overridden using the In [3]:
import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", color="sex", labels=dict(total_bill="Total Bill ($)", tip="Tip ($)", sex="Payer Gender") ) fig.show() The PX In [4]:
import plotly.express as px fig = px.bar(x=["Apples", "Oranges"], y=[10,20], color=["Here", "There"], labels=dict(x="Fruit", y="Amount", color="Place") ) fig.show() Rotating tick labels in Dash¶Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run Get started with the official Dash docs and learn how to effortlessly style & publish apps like this with Dash Enterprise or Plotly Cloud. Out[5]:
Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now. Moving Tick Labels Inside the Plot¶The In [6]:
import plotly.express as px df = px.data.stocks(indexed=True)-1 fig = px.bar(df, x=df.index, y="GOOG") fig.update_yaxes(ticklabelposition="inside top", title=None) fig.show() Specifying Label Aliases¶New in 5.14 With In [7]:
import plotly.express as px import pandas as pd df = px.data.tips() df = df[df.day.isin(['Sat', 'Sun'])].groupby(by='day', as_index=False).sum(numeric_only=True) fig = px.bar(df, x="day", y="total_bill") fig.update_xaxes(labelalias=dict(Sat="Saturday", Sun="Sunday")) fig.show() Set axis title text with Graph Objects¶Axis titles are set using the nested In [8]:
import plotly.express as px fig = px.line(y=[1, 0]) fig.update_xaxes(title_text='Time') fig.update_yaxes(title_text='Value A') fig.show() Set axis title position¶This example sets In [9]:
import plotly.graph_objects as go fig = go.Figure(go.Scatter( mode = "lines+markers", y = [4, 1, 3], x = ["December", "January", "February"])) fig.update_xaxes( tickangle = 90, title_text = "Month", title_font = {"size": 20}, title_standoff = 25) fig.update_yaxes( title_text = "Temperature", title_standoff = 25) fig.show() Set axis title font¶Here is an example that configures the font family, size, and color for the axis titles in a figure created using Plotly Express. In [10]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(title_font=dict(size=18, family='Courier', color='crimson')) fig.update_yaxes(title_font=dict(size=18, family='Courier', color='crimson')) fig.show() Tick Placement, Color, and Style¶Toggling axis tick marks¶Axis tick marks are disabled by default for the default Here is an example of turning on inside x-axis and y-axis ticks in a faceted figure created using Plotly Express. Note how the In [11]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(ticks="inside") fig.update_yaxes(ticks="inside", col=1) fig.show() Set number of tick marks (and grid lines)¶The approximate number of ticks displayed for an axis can be specified using the Here is an example of updating the y-axes of a figure created using Plotly Express to display approximately 20 ticks. In [12]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(nticks=20) fig.show() Set start position and distance between ticks¶The Here is an example of updating the y axis of a figure created using Plotly Express to position the ticks at intervals of 0.5, starting at 0.25. In [13]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(tick0=0.25, dtick=0.5) fig.show() Set exact location of axis ticks¶It is possible to configure an axis to display ticks at a set of predefined locations by setting the Here is an example of setting the exact location of ticks on the y axes of a figure created using Plotly Express. In [14]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(tickvals=[5.1, 5.9, 6.3, 7.5]) fig.show() Style tick marks¶As discussed above, tick marks are disabled by default in the default The appearance of these tick marks can be customized by setting their length ( Here is an example of enabling and styling the tick marks of a faceted figure created using Plotly Express. Note how the In [15]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(ticks="outside", tickwidth=2, tickcolor='crimson', ticklen=10) fig.update_yaxes(ticks="outside", tickwidth=2, tickcolor='crimson', ticklen=10, col=1) fig.show() Step for tick labels¶New in v5.6 You can set a step for tick labels with In [16]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(ticklabelstep=2) fig.show() Toggling axis labels¶The axis tick mark labels can be disabled by setting the Here is an example of disabling tick labels in all subplots for a faceted figure created using Plotly Express. In [17]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(showticklabels=False) fig.update_yaxes(showticklabels=False) fig.show() Set axis label rotation and font¶The orientation of the axis tick mark labels is configured using the Here is an example of rotating the x-axis tick labels by 45 degrees, and customizing their font properties, in a faceted histogram figure created using Plotly Express. In [18]:
import plotly.express as px df = px.data.tips() fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', color='crimson', size=14)) fig.show() Auto Tick Angle Options¶New in 5.19 If In [19]:
import plotly.express as px df = px.data.gapminder() df = df.loc[(df.continent=="Asia") & (df.year==1992)] fig = px.histogram(df, x=df.country, y=df.gdpPercap) fig.update_xaxes(autotickangles=[45, 60, 90]) fig.show() Enumerated Ticks with Tickvals and Ticktext¶The Here is an example. In [20]:
import plotly.graph_objects as go import pandas as pd apple_df = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv" ) # Convert 'Date' column to datetime format apple_df['Date'] = pd.to_datetime(apple_df['Date']) # Set 'Date' column as index apple_df.set_index('Date', inplace=True) # Filter for 2016 apple_df_2016 = apple_df.loc['2016'] # Create figure and add line fig = go.Figure() fig.add_trace(go.Scatter( x=apple_df_2016.index, y=apple_df_2016["AAPL.High"], mode="lines" )) # Set custom x-axis labels fig.update_xaxes( ticktext=["End of Q1", "End of Q2", "End of Q3", "End of Q4"], tickvals=["2016-04-01", "2016-07-01", "2016-10-01", apple_df_2016.index.max()], ) # Prefix y-axis tick labels with dollar sign fig.update_yaxes(tickprefix="$") # Set figure title fig.update_layout(title_text="Apple Stock Price") fig.show() Adding minor ticks¶new in 5.8 You can position and style minor ticks on a Cartesian axis using the In the following example, we add minor ticks to the x-axis and then to the y-axis. For the y-axis we add ticks on the inside: In [21]:
import plotly.express as px import pandas as pd df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", color="sex") fig.update_xaxes(minor=dict(ticklen=6, tickcolor="black", showgrid=True)) fig.update_yaxes(minor_ticks="inside") fig.show() Adjust Tick Label Positions¶New in 5.23 You can adjust tick label positions by moving them a number of pixels away from the axis using In this example, Here, In [22]:
import plotly.express as px import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') fig = px.line(df, x='Date', y='AAPL.High') fig.update_layout( xaxis=dict( ticks='outside', ticklen=10, ticklabelshift=25, ticklabelstandoff=15 ) ) fig.show() Use Minor Tick for Label¶New in 5.23 On date or linear axes, use To draw the label for the minor tick before each major tick, set In [23]:
import plotly.express as px import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') fig = px.line(df, x='Date', y='AAPL.High') fig.update_layout( xaxis=dict( minor=dict(ticks='outside'), ticks='outside', ticklen=10, ticklabelindex=-1 ) ) fig.show() In [24]:
import plotly.express as px fig = px.line(y=[1, 0]) fig.update_xaxes(showgrid=False) fig.update_yaxes(showgrid=False) fig.show() Toggling Axis zero lines¶The lines passing through zero can be disabled as well by setting the In [25]:
import plotly.express as px fig = px.line(y=[1, 0]) fig.update_xaxes(showgrid=False, zeroline=False) fig.update_yaxes(showgrid=False, zeroline=False) fig.show() Styling and Coloring Axes and the Zero-Line¶Styling axis lines¶The Here is an example of enabling the x and y axis lines, and customizing their width and color, for a faceted histogram created with Plotly Express. In [26]:
import plotly.express as px df = px.data.tips() fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(showline=True, linewidth=2, linecolor='black') fig.update_yaxes(showline=True, linewidth=2, linecolor='black') fig.show() Mirroring axis lines¶Axis lines can be mirrored to the opposite side of the plotting area by setting the Here is an example of mirroring the x and y axis lines in a faceted histogram created using Plotly Express. In [27]:
import plotly.express as px df = px.data.tips() fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True) fig.update_yaxes(showline=True, linewidth=2, linecolor='black', mirror=True) fig.show() Styling grid lines¶The width and color of axis grid lines are controlled by the Here is an example of customizing the grid line width and color for a faceted scatter plot created with Plotly Express In [28]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightPink') fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='LightPink') fig.show() new in 5.8 By default grid lines are In [29]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(gridcolor='black', griddash='dash', minor_griddash="dot") fig.show() Styling zero lines¶The width and color of axis zero lines are controlled by the Here is an example of configuring the zero line width and color for a simple figure using the In [30]:
import plotly.express as px fig = px.line(y=[1, 0]) fig.update_xaxes(zeroline=True, zerolinewidth=2, zerolinecolor='LightPink') fig.update_yaxes(zeroline=True, zerolinewidth=2, zerolinecolor='LightPink') fig.show() Controlling Zero Line Layer¶New in 6.3 By default, zero lines are displayed below traces. Set In [31]:
import plotly.graph_objects as go x = ['A', 'B', 'C', 'D', 'A'] y = [2, 0, 4, -3, 2] fig = go.Figure( data=[ go.Scatter( x=x, y=y, fill='toself', mode='none', fillcolor='lightpink' ) ], layout=dict( yaxis=dict( zerolinelayer="above traces" # Change to "below traces" to see the difference ), ) ) fig.show() Setting the Range of Axes Manually¶The visible x and y axis range can be configured manually by setting the Here's an example of manually specifying the x and y axis range for a faceted scatter plot created with Plotly Express. In [32]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(range=[1.5, 4.5]) fig.update_yaxes(range=[3, 9]) fig.show() Exclude Inside Tick Labels from Range¶New in 5.18 You can use In this example, we have a y axis with In [33]:
import plotly.express as px df = px.data.stocks(indexed=True) fig = px.line(df, df.index, y="GOOG") fig.update_yaxes(ticklabelposition="inside", title=dict(text="Price")) fig.update_xaxes(insiderange=['2018-10-01', '2019-01-01'], title=dict(text="Date")) fig.show() Setting only a Lower or Upper Bound for Range¶New in 5.17 You can also set just a lower or upper bound manually and have autorange applied to the other bound by setting it to In [34]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(range=[None, 4.5]) fig.update_yaxes(range=[3, None]) fig.show() Setting a Maximum and Minimum Allowed Axis Value¶New in 5.17 When setting a range manually, you can also set a In [35]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") fig.update_xaxes(range=[1.5, 4.5], minallowed=1) fig.update_yaxes(range=[3, 9], maxallowed=10) fig.show() Disabling Pan/Zoom on Axes (Fixed Range)¶Pan/Zoom can be disabled for a given axis by setting In [36]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(fixedrange=True) fig.show() Fixed Ratio Axes¶The Here is an example of anchoring the scale of the x and y axis with a scale ratio of 1. Notice how the zoom box is constrained to prevent the distortion of the shape of the line plot. In [37]:
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3], y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0] )) fig.update_layout( width = 800, height = 500, title = "fixed-ratio axes" ) fig.update_yaxes( scaleanchor = "x", scaleratio = 1, ) fig.show() Fixed Ratio Axes with Compressed domain¶If an axis needs to be compressed (either due to its own In [38]:
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3], y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0] )) fig.update_layout( width = 800, height = 500, title = "fixed-ratio axes with compressed axes" ) fig.update_xaxes( range=[-1,4], # sets the range of xaxis constrain="domain", # meanwhile compresses the xaxis by decreasing its "domain" ) fig.update_yaxes( scaleanchor = "x", scaleratio = 1 ) fig.show() Decreasing the domain spanned by an axis¶In the example below, the x and y axis are anchored together, and the range of the In [39]:
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3], y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0] )) fig.update_layout( width = 800, height = 500, title = "fixed-ratio axes" ) fig.update_xaxes( scaleanchor = "x", scaleratio = 1, ) fig.update_yaxes( range=(-0.5, 3.5), constrain='domain' ) fig.show() Reversed Axes¶You can tell plotly's automatic axis range calculation logic to reverse the direction of an axis by setting the Here is an example of reversing the direction of the y axes for a faceted scatter plot created using Plotly Express. In [40]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(autorange="reversed") fig.show() Reversed Axes with Range ( Min/Max ) Specified¶The direction of an axis can be reversed when manually setting the range extents by specifying a list containing the upper bound followed by the lower bound (rather that the lower followed by the upper) as the Here is an example of manually setting the reversed range of the y axes in a faceted scatter plot figure created using Plotly Express. In [41]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(range=[9, 3]) fig.show() New in 5.17 To use a reversed axis while specifying only a lower bound for the range, set In [42]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(range=[9, None], autorange="min reversed") fig.show() New in 5.17 To use a reversed axis while specifying only an upper bound for the range, set In [43]:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(range=[None, 3], autorange="max reversed") fig.show() Axis range for log axis type¶If you are using a In [44]:
import plotly.express as px import numpy as np x = np.linspace(1, 200, 30) fig = px.scatter(x=x, y=x**3, log_x=True, log_y=True, range_x=[0.8, 250]) fig.show() In [45]:
import plotly.graph_objects as go import numpy as np x = np.linspace(1, 200, 30) fig = go.Figure(go.Scatter(x=x, y=x**3)) fig.update_xaxes(type="log", range=[np.log10(0.8), np.log10(250)]) fig.update_yaxes(type="log") fig.show() Setting the domain of the axis¶In [46]:
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3], y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0] )) fig.update_xaxes(domain=(0.25, 0.75)) fig.update_yaxes(domain=(0.25, 0.75)) fig.show() Synchronizing axes in subplots with |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |