### Basic Data Preparation and Plotting for adjust_text Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Prepares data for a plot and creates initial text labels without adjustment. This is a setup step before applying adjust_text, demonstrating data structuring and initial plotting. ```python together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)] together.sort() text = [x for (x,y,z) in together] eucs = [y for (x,y,z) in together] covers = [z for (x,y,z) in together] def plot_eucs_covers(): plt.plot(eucs,covers,color="black", alpha=0.5) texts = [] for xt, yt, s in zip(eucs, covers, text): texts.append(plt.text(xt, yt, s)) return texts _ = plot_eucs_covers() ``` -------------------------------- ### Setup for Interactive Text Adjustment with adjust_text and Matplotlib Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Interactive_example.ipynb This code snippet sets up the necessary environment for interactive plotting using Matplotlib's ipympl backend and imports the adjust_text function. It initializes random data points for plotting. ```python %matplotlib ipympl import numpy as np from adjustText import adjust_text import matplotlib.pyplot as plt ``` -------------------------------- ### Install adjustText using pip Source: https://github.com/phlya/adjusttext/blob/master/README.md Installs the adjustText library from the Python Package Index (PyPI). This is the standard method for installing Python packages. ```bash pip install adjustText ``` -------------------------------- ### Basic adjust_text Usage with Scatter Plot Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Demonstrates the fundamental usage of adjust_text by plotting points and then adjusting the positions of their corresponding text labels. This example shows the default behavior of the adjustment algorithm. ```python np.random.seed(0) x, y = np.random.random((2,30)) fig, ax = plt.subplots() plt.plot(x, y, 'bo') texts = [plt.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))] adjust_text(texts) ``` -------------------------------- ### Install adjustText from GitHub Source: https://github.com/phlya/adjusttext/blob/master/README.md Installs the latest version of adjustText directly from its GitHub repository. This is useful for accessing the most recent features or bug fixes before they are officially released on PyPI. ```bash pip install https://github.com/Phlya/AdjustText/archive/master.zip ``` -------------------------------- ### Import adjustText and Matplotlib Libraries Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Initializes necessary libraries for plotting and text adjustment. This includes Matplotlib for plotting and adjust_text from the adjustText library. It also imports numpy and pandas for data manipulation. ```python import matplotlib.pyplot as plt from adjustText import adjust_text import numpy as np import pandas as pd ``` -------------------------------- ### Install adjustText using conda Source: https://github.com/phlya/adjusttext/blob/master/README.md Installs the adjustText library using the conda package manager from the conda-forge channel. This is an alternative installation method, particularly useful for users already managing their environments with conda. ```bash conda install -c conda-forge adjusttext ``` -------------------------------- ### Adjust Text with Expansion and Arrows Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Shows how to configure adjust_text with custom parameters, specifically `expand` to adjust the bounding box size and `arrowprops` to draw arrows connecting labels to their original points. This improves clarity when labels are moved significantly. ```python fig, ax = plt.subplots() ax.plot(x, y, 'bo') texts = [ax.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))] adjust_text(texts, expand=(1.2, 2), # expand text bounding boxes by 1.2 fold in x direction and 2 fold in y direction arrowprops=dict(arrowstyle='->', color='red') # ensure the labeling is clear by adding arrows ) ``` -------------------------------- ### Creating Dense Labeled Plots with adjust_text and Matplotlib Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This example illustrates how to create complex, data-rich plots with dense labels using adjust_text. It leverages dictionaries of language-specific data and customizes plotting parameters for better label arrangement. This is useful for visualizing linguistic data or other dense datasets. ```python from matplotlib import gridspec d1={'Afrikaans': 1.35, 'Amharic': 9.51, 'AncientGreek': 11.62, 'Arabic': 9.22, 'Armenian': 2.92, 'Bambara': 0.1, 'Basque': 8.46, 'Belarusian': 2.48, 'Breton': 24.0, 'Bulgarian': 5.12, 'Buryat': 0.0, 'Cantonese': 4.5, 'Catalan': 1.97, 'Chinese': 0.05, 'Coptic': 4.41, 'Croatian': 4.17, 'Czech': 8.74, 'Danish': 14.58, 'Dutch': 15.3, 'English': 0.79, 'Erzya': 21.74, 'Estonian': 17.1, 'Faroese': 8.92, 'Finnish': 5.82, 'French': 2.44, 'Galician': 7.0, 'German': 20.6, 'Gothic': 11.11, 'Greek': 4.88, 'Hebrew': 1.48, 'Hindi': 0.16, 'Hungarian': 7.46, 'Indonesian': 1.12, 'Irish': 98.16, 'Italian': 6.8, 'Japanese': 0.0, 'Kazakh': 0.46, 'Komi': 17.24, 'Korean': 0.04, 'Kurmanji': 0.37, 'Latin': 6.14, 'Latvian': 3.34, 'Lithuanian': 0.98, 'Maltese': 0.0, 'Marathi': 1.95, 'Naija': 0.11, 'NorthSami': 4.48, 'Norwegian': 12.59, 'OldChurchSlavonic': 13.42, 'OldFrench': 10.6, 'Persian': 2.45, 'Polish': 15.49, 'Portuguese': 3.1, 'Romanian': 12.75, 'Russian': 5.9, 'Sanskrit': 9.46, 'Serbian': 9.7, 'Slovak': 11.67, 'Slovenian': 12.08, 'Spanish': 3.41, 'Swedish': 13.36, 'SwedishSign': 18.89, 'Tagalog': 100.0, 'Tamil': 5.61, 'Telugu': 0.0, 'Thai': 0.0, 'Turkish': 9.95, 'Ukrainian': 5.39, 'UpperSorbian': 5.66, 'Urdu': 0.21, 'Uyghur': 1.96, 'Vietnamese': 0} d2={'Afrikaans': 2.63, 'Amharic': 0.59, 'AncientGreek': 41.61, 'Arabic': 73.29, 'Armenian': 20.6, 'Bambara': 0.0, 'Basque': 18.53, 'Belarusian': 33.54, 'Breton': 53.99, 'Bulgarian': 30.08, 'Buryat': 0.38, 'Cantonese': 5.31, 'Catalan': 23.57, 'Chinese': 0.24, 'Coptic': 28.02, 'Croatian': 28.64, 'Czech': 37.94, 'Danish': 14.95, 'Dutch': 21.98, 'English': 9.93, 'Erzya': 42.54, 'Estonian': 38.92, 'Faroese': 16.07, 'Finnish': 23.02, 'French': 5.85, 'Galician': 19.7, 'German': 19.77, 'Gothic': 49.52, 'Greek': 35.74, 'Hebrew': 35.52, 'Hindi': 0.39, 'Hungarian': 28.8, 'Indonesian': 4.5, 'Irish': 98.64, 'Italian': 25.96, 'Japanese': 0.0, 'Kazakh': 0.44, 'Komi': 20.17, 'Korean': 0.04, 'Kurmanji': 0.46, 'Latin': 32.51, 'Latvian': 37.48, 'Lithuanian': 39.38, 'Maltese': 10.34, 'Marathi': 2.78, 'Naija': 4.44, 'NorthSami': 32.38, 'Norwegian': 19.04, 'OldChurchSlavonic': 53.81, 'OldFrench': 35.13, 'Persian': 0.73, 'Polish': 36.67, 'Portuguese': 13.93, 'Romanian': 30.23, 'Russian': 33.52, 'Sanskrit': 31.1, 'Serbian': 25.7, 'Slovak': 39.69, 'Slovenian': 31.77, 'Spanish': 22.06, 'Swedish': 19.8, 'SwedishSign': 18.69, 'Tagalog': 97.92, 'Tamil': 0.55, 'Telugu': 0.95, 'Thai': 0.15, 'Turkish': 4.67, 'Ukrainian': 32.81, 'UpperSorbian': 23.85, 'Urdu': 0.18, 'Uyghur': 4.06, 'Vietnamese': 1.62} ``` -------------------------------- ### Import Libraries for adjustText and Matplotlib Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Imports necessary libraries: matplotlib.pyplot for plotting, adjust_text for label adjustment, numpy for numerical operations, and pandas for data manipulation. Matplotlib version 2.0 is assumed for the examples. ```python %matplotlib inline import matplotlib.pyplot as plt # Matplotlib 2.0 shown here from adjustText import adjust_text import numpy as np import pandas as pd ``` -------------------------------- ### Language Distribution Visualization with adjust_text (Python) Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb This code snippet demonstrates visualizing the distribution of languages using matplotlib and the adjust_text library. It plots data points and uses adjust_text to manage label placement, preventing overlap and improving the clarity of the visualization, especially when dealing with many labels. ```python from matplotlib import patches d={'Afrikaans': 1.93, 'Amharic': 44.56, 'AncientGreek': 33.06, 'Arabic': 65.9, 'Armenian': 20.16, 'Bambara': 0.13, 'Basque': 20.4, 'Belarusian': 26.28, 'Breton': 53.21, 'Bulgarian': 25.77, 'Buryat': 0.4, 'Cantonese': 4.4, 'Catalan': 19.14, 'Chinese': 0.19, 'Coptic': 11.67, 'Croatian': 24.72, 'Czech': 36.6, 'Danish': 16.38, 'Dutch': 21.72, 'English': 4.9, 'Erzya': 40.76, 'Estonian': 36.45, 'Faroese': 14.19, 'Finnish': 17.88, 'French': 4.67, 'Galician': 17.52, 'German': 21.45, 'Gothic': 34.23, 'Greek': 34.27, ``` -------------------------------- ### Create Patches for Language Family Distribution Visualization Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This Python code snippet imports the `patches` module from Matplotlib, which is used for creating graphical elements like rectangles, circles, and polygons. This is often used in conjunction with `adjust_text` for creating custom visualizations of data distributions. ```python from matplotlib import patches ``` -------------------------------- ### Applying adjust_text with Custom Arrows to Prepared Data Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Applies adjust_text to the previously plotted data, incorporating custom arrow properties. This example demonstrates how to refine the visual connection between labels and data points. ```python texts = plot_eucs_covers() adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r', lw=0.5)) ``` -------------------------------- ### Adjusting a Single Label in a Dense Scatter Plot Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Shows how to adjust a single label in a scatter plot with many points using adjust_text. This example highlights the improvement in clarity when a specific point needs to be identified. ```python def plot_scatter(adjust=False): np.random.seed(100) x, y = np.random.random((2,400)) fig, ax = plt.subplots() ax.plot(x, y, 'bo') texts = [plt.text(x[0], y[0], 'Something')] if adjust: plt.title(str( adjust_text(texts, x, y, arrowprops=dict(arrowstyle='->', color='red')) )+' iterations') _ = plot_scatter() plot_scatter(adjust=True) ``` -------------------------------- ### Visualize Language Data with adjustText and Matplotlib Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This Python script visualizes language data, plotting distributions and using adjustText to manage overlapping labels. It relies on Matplotlib for plotting and pandas for data handling. The function takes language data and styling parameters to generate a scatter plot. ```python import pandas as pd import matplotlib.pyplot as plt from adjustText import adjust_text # Assuming d1, d2, langnameGroup, groupColors, groupMarkers are defined # Example definitions (replace with actual data if available): d1 = {'English': 10, 'French': 20, 'German': 30} d2 = {'English': 5, 'French': 15, 'German': 25} langnameGroup = {'English': 'Indo-European-Germanic', 'French': 'Indo-European-Romance', 'German': 'Indo-European-Germanic'} groupColors = {'Indo-European-Romance': 'brown', 'Indo-European-Germanic': 'olive'} groupMarkers = {'Indo-European-Romance': '<', 'Indo-European-Germanic': 'v'} col1 = pd.Series(d1) col2 = pd.Series(d2) c = [groupColors.get(langnameGroup[label], 'k') for label in col1.index] m = [groupMarkers.get(langnameGroup[label], 'o') for label in col1.index] fig = plt.figure(figsize=(10, 10)) import matplotlib.gridspec as gridspec # Define grid spec for subplots gs = gridspec.GridSpec(2, 2, width_ratios=[1, 25], height_ratios=[25, 1]) aa = plt.subplot(gs[0]) ax = plt.subplot(gs[1]) bb = plt.subplot(gs[3]) li, la = (-15, 100) plt.xlim(li, la) plt.ylim(li, la) ax.set_xlim([li, la]) ax.set_ylim([li, la]) aa.set_xlim([0, 1]) aa.set_ylim([li, la]) bb.set_ylim([0, 1]) # Set ticks for the main plot ax.set_xticks([0, 50, 100], minor=False) ax.set_xticks([0, 25, 50, 75, 100], minor=True) ax.set_yticks([0, 50, 100], minor=False) ax.set_yticks([0, 25, 50, 75, 100], minor=True) ax.grid(which='both', axis='both', alpha=.5) ax.plot([0, 1], [0, 1], transform=ax.transAxes, alpha=.5, color="gray") # diagonal # Hide ticks for subplots aa.set_xticks([], minor=False) aa.set_yticks([], minor=False) bb.set_xticks([], minor=False) bb.set_yticks([], minor=False) # Scatter plot for main data for xx, yy, cc, mm in zip(col1, col2, c, m): ax.scatter(xx, yy, marker=mm, c=cc) # Scatter plots for marginal distributions aa.scatter([0.5 for _ in col1], col2, c=c, alpha=0.5) bb.scatter(col1, [0.5 for _ in col2], c=c, alpha=0.5) # Add text labels and adjust them texts = [] for label, x, y in zip(col1.index, col1, col2): texts.append(ax.text(x, y, label, color=groupColors.get(langnameGroup[label], 'k'), fontsize=8)) adjust_text(texts, col1, col2, ax=ax, precision=0.001, expand_text=(1.01, 1.05), expand_points=(1.01, 1.05), force_text=(0.01, 0.25), force_points=(0.01, 0.25), arrowprops=dict(arrowstyle='-', color='gray', alpha=.5)) # To display the plot: # plt.show() ``` -------------------------------- ### Display Matplotlib Figure Object Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This code snippet shows how to represent a Matplotlib figure object, typically resulting from plotting operations. It returns a string representation of the figure's size and axes. ```python
``` -------------------------------- ### Conditional Text Adjustment for Single Label Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Illustrates adjusting a single text label on a scatter plot, particularly useful when one point is of special interest. The example includes parameters to expand the text bounding box and add arrows, and shows the effect with and without adjustment. ```python def plot_scatter(adjust=False): np.random.seed(100) x, y = np.random.random((2,400)) fig, ax = plt.subplots() ax.plot(x, y, 'bo') texts = [plt.text(x[0], y[0], 'Something')] if adjust: texts, patches = adjust_text(texts, x=x, y=y, expand=(1.1, 1.5), arrowprops=dict(arrowstyle='->', color='red')) plot_scatter() plot_scatter(adjust=True) ``` -------------------------------- ### Scatter Plot with Language Data and Text Adjustment (Python) Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb This snippet generates a scatter plot visualizing language data. It utilizes matplotlib for plotting and adjust_text to prevent label overlapping. The code maps language families to colors and markers, and adjusts text labels for better readability. ```python langnameGroup={"AncientGreek":"Indo-European", "Arabic":"Semitic", "Basque":"isolate", "Belarusian":"Indo-European-Baltoslavic", "Bulgarian":"Indo-European-Baltoslavic", "Cantonese":"Sino-Austronesian", "Catalan":"Indo-European-Romance", "Chinese":"Sino-Austronesian", "Coptic":"Afroasiatic", "Croatian":"Indo-European-Baltoslavic", "Czech":"Indo-European-Baltoslavic", "Danish":"Indo-European-Germanic", "Dutch":"Indo-European-Germanic", "English":"Indo-European-Germanic", "Estonian":"Agglutinating", "Finnish":"Agglutinating", "French":"Indo-European-Romance", "Galician":"Indo-European-Romance", "German":"Indo-European-Germanic", "Gothic":"Indo-European-Germanic", "Greek":"Indo-European", "Hebrew":"Semitic", "Hindi":"Indo-European", "Hungarian":"Agglutinating", "Indonesian":"Sino-Austronesian", "Irish":"Indo-European", "Italian":"Indo-European-Romance", "Japanese":"Agglutinating", "Kazakh":"Agglutinating", "Korean":"Agglutinating", "Latin":"Indo-European-Romance", "Latvian":"Indo-European-Baltoslavic", "Lithuanian":"Indo-European-Baltoslavic", "Norwegian":"Indo-European-Germanic", "OldChurchSlavonic":"Indo-European-Baltoslavic", "Persian":"Indo-European", "Polish":"Indo-European-Baltoslavic", "Portuguese":"Indo-European-Romance", "Romanian":"Indo-European-Romance", "Russian":"Indo-European-Baltoslavic", "Sanskrit":"Indo-European", "Slovak":"Indo-European-Baltoslavic", "Slovenian":"Indo-European-Baltoslavic", "Spanish":"Indo-European-Romance", "Swedish":"Indo-European-Germanic", "Tamil":"Dravidian", "Turkish":"Agglutinating", "Ukrainian":"Indo-European-Baltoslavic", "Urdu":"Indo-European", "Uyghur":"Agglutinating", "Vietnamese":"Sino-Austronesian", 'Afrikaans':'Indo-European-Germanic', 'SwedishSign':'Indo-European-Germanic', 'Kurmanji':'Indo-European', 'NorthSami':'Agglutinating', 'UpperSorbian':"Indo-European-Baltoslavic", 'Buryat':'Agglutinating', 'Telugu':'Dravidian', 'Serbian':"Indo-European-Baltoslavic", 'Marathi':'Indo-European','Naija':"Indo-European-Germanic", "OldFrench":"Indo-European-Romance", "Maltese":"Semitic", "Thai":"Sino-Austronesian","Amharic":"Afroasiatic", 'Erzya': 'Agglutinating', 'Faroese':"Indo-European-Germanic", 'Tagalog':"Sino-Austronesian", 'Bambara':'Niger-Congo', 'Breton':"Indo-European", 'Armenian':"Indo-European", 'Komi': 'Agglutinating'} groupColors={"Indo-European-Romance":'brown',"Indo-European-Baltoslavic":'purple',"Indo-European-Germanic":'olive',"Indo-European":'royalBlue',"Sino-Austronesian":'limeGreen', "Agglutinating":'red'} groupMarkers={"Indo-European-Romance":'<',"Indo-European-Baltoslavic":'^',"Indo-European-Germanic":'v',"Indo-European":'>',"Sino-Austronesian":'s', "Agglutinating":'+'} col1 = pd.Series(d1) col2 = pd.Series(d2) c=[groupColors.get(langnameGroup[label],'k') for label in col1.index] m=[groupMarkers.get(langnameGroup[label],'o') for label in col1.index] fig = plt.figure(figsize=(10,10)) gs = gridspec.GridSpec(2, 2, width_ratios=[1, 25], height_ratios=[25, 1]) aa = plt.subplot(gs[0]) ax = plt.subplot(gs[1]) bb = plt.subplot(gs[3]) li,la = (-15,100) plt.xlim(li,la) plt.ylim(li,la) ax.set_xlim([li,la]) ax.set_ylim([li,la]) aa.set_xlim([0, 1]) aa.set_ylim([li,la]) bb.set_ylim([0, 1]) ax.set_xticks([0, 50,100], minor=False) # only the 50% is major ax.set_xticks([0,25,50,75,100], minor=True) # all 10th are minor ax.set_yticks([0, 50,100], minor=False) # only the 50% is major ax.set_yticks([0,25,50,75,100], minor=True) # all 10th are minor ax.grid(which='both', axis='both',alpha=.5) # draw grid ax.plot([0, 1], [0, 1], transform=ax.transAxes, alpha=.5, color="gray") # diagonal aa.set_xticks([], minor=False) aa.set_yticks([], minor=False) bb.set_xticks([], minor=False) bb.set_yticks([], minor=False) for xx, yy, cc, mm in zip(col1, col2, c, m): ax.scatter(xx, yy, marker=mm, c=cc) aa.scatter([0.5 for _ in col1], col2, c=c, alpha=0.5) bb.scatter(col1, [0.5 for _ in col2], c=c, alpha=0.5) texts=[] for label, x, y in zip(col1.index, col1, col2): texts+=[ax.text(x, y, label, color=groupColors.get(langnameGroup[label],'k'), fontsize=8, ha='center', va='center')] # for adjustText adjust_text(texts, ax=ax, arrowprops=dict(arrowstyle='-', color='gray', alpha=.5)) ``` -------------------------------- ### Language Data Visualization with adjust_text Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This snippet demonstrates how to visualize language data using a scatter plot and the adjust_text library in Python. It processes language data, assigns colors based on language groups, and uses adjust_text to prevent labels from overlapping. Dependencies include pandas, matplotlib, and adjust_text. ```python import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np from adjustText import adjust_text d = {'Faroese': 14.19, 'Finnish': 17.88, 'French': 4.67, 'Galician': 17.52, 'German': 21.45, 'Gothic': 34.23, 'Greek': 34.27, 'Hebrew': 28.75, 'Hindi': 1.4, 'Hungarian': 27.91, 'Indonesian': 2.6, 'Irish': 87.93, 'Italian': 22.75, 'Japanese': 0.0, 'Kazakh': 0.89, 'Komi': 19.34, 'Korean': 0.35, 'Kurmanji': 0.61, 'Latin': 27.5, 'Latvian': 24.22, 'Lithuanian': 28.8, 'Maltese': 7.26, 'Marathi': 2.64, 'Naija': 2.29, 'NorthSami': 21.18, 'Norwegian': 19.43, 'OldChurchSlavonic': 37.51, 'OldFrench': 20.14, 'Persian': 0.99, 'Polish': 30.55, 'Portuguese': 12.84, 'Romanian': 29.0, 'Russian': 29.15, 'Sanskrit': 20.09, 'Serbian': 24.1, 'Slovak': 33.18, 'Slovenian': 31.72, 'Spanish': 19.09, 'Swedish': 18.84, 'SwedishSign': 19.23, 'Tagalog': 98.18, 'Tamil': 2.95, 'Telugu': 0.85, 'Thai': 0.06, 'Turkish': 6.38, 'Ukrainian': 26.38, 'UpperSorbian': 22.03, 'Urdu': 0.74, 'Uyghur': 3.58, 'Vietnamese': 1.78} langnameGroup={"AncientGreek":"Indo-European", "Arabic":"Semitic", "Basque":"isolate", "Belarusian":"Indo-European-Baltoslavic", "Bulgarian":"Indo-European-Baltoslavic", "Cantonese":"Sino-Austronesian", "Catalan":"Indo-European-Romance", "Chinese":"Sino-Austronesian", "Coptic":"Afroasiatic", "Croatian":"Indo-European-Baltoslavic", "Czech":"Indo-European-Baltoslavic", "Danish":"Indo-European-Germanic", "Dutch":"Indo-European-Germanic", "English":"Indo-European-Germanic", "Estonian":"Agglutinating", "Finnish":"Agglutinating", "French":"Indo-European-Romance", "Galician":"Indo-European-Romance", "German":"Indo-European-Germanic", "Gothic":"Indo-European-Germanic", "Greek":"Indo-European", "Hebrew":"Semitic", "Hindi":"Indo-European", "Hungarian":"Agglutinating", "Indonesian":"Sino-Austronesian", "Irish":"Indo-European", "Italian":"Indo-European-Romance", "Japanese":"Agglutinating", "Kazakh":"Agglutinating", "Korean":"Agglutinating", "Latin":"Indo-European-Romance", "Latvian":"Indo-European-Baltoslavic", "Lithuanian":"Indo-European-Baltoslavic", "Norwegian":"Indo-European-Germanic", "OldChurchSlavonic":"Indo-European-Baltoslavic", "Persian":"Indo-European", "Polish":"Indo-European-Baltoslavic", "Portuguese":"Indo-European-Romance", "Romanian":"Indo-European-Romance", "Russian":"Indo-European-Baltoslavic", "Sanskrit":"Indo-European", "Slovak":"Indo-European-Baltoslavic", "Slovenian":"Indo-European-Baltoslavic", "Spanish":"Indo-European-Romance", "Swedish":"Indo-European-Germanic", "Tamil":"Dravidian", "Turkish":"Agglutinating", "Ukrainian":"Indo-European-Baltoslavic", "Urdu":"Indo-European", "Uyghur":"Agglutinating", "Vietnamese":"Sino-Austronesian",'Afrikaans':'Indo-European-Germanic', 'SwedishSign':'Indo-European-Germanic', 'Kurmanji':'Indo-European', 'NorthSami':'Agglutinating', 'UpperSorbian':"Indo-European-Baltoslavic", 'Buryat':'Agglutinating', 'Telugu':'Dravidian', 'Serbian':"Indo-European-Baltoslavic", 'Marathi':'Indo-European','Naija':"Indo-European-Germanic", "OldFrench":"Indo-European-Romance", "Maltese":"Semitic", "Thai":"Sino-Austronesian","Amharic":"Afroasiatic", 'Erzya': 'Agglutinating', 'Faroese':"Indo-European-Germanic", 'Tagalog':"Sino-Austronesian", 'Bambara':'Niger-Congo', 'Breton':"Indo-European", 'Armenian':"Indo-European", 'Komi': 'Agglutinating'} groupColors={"Indo-European-Romance":'brown',"Indo-European-Baltoslavic":'purple',"Indo-European-Germanic":'olive',"Indo-European":'royalBlue',"Sino-Austronesian":'limeGreen', "Agglutinating":'red'} df = pd.Series(d) c=[groupColors.get(langnameGroup[label],'k') for label in df.index] fig, aa = plt.subplots(figsize=(7, 9)) aa.axes.get_xaxis().set_visible(False) aa.set_xlim(-10, 0.1) aa.set_ylim(-1, 101) aa.scatter([0 for _ in df], df, c=c, alpha=0.5, edgecolors='none') aa.spines['left'].set_visible(False) aa.spines['top'].set_visible(False) aa.spines['bottom'].set_visible(False) aa.yaxis.set_label_position('right') aa.yaxis.set_ticks_position('right') plt.tight_layout() patch = patches.Rectangle((-0.1, 0), 0.2, 100, fill=False, alpha=0) # We add a rectangle to make sure the labels don't move ot the right aa.add_patch(patch) texts=[] np.random.seed(0) for label, y in zip(df.index, df): texts+=[aa.text(-.1+np.random.random()/1000, y, label, # A small random shift prevents labels which have exactly the same coordinates from being stuck together # (not a problem in this example really, but wanted to mention this possibility) color=groupColors.get(langnameGroup[label],'k'), fontsize=8)] adjust_text(texts, [0 for _ in df], df, ha='right', va='center', add_objects=[patch], precision=0.005, # We need higher precision than default to make this look perfect expand_text=(1.05, 1), # We want them to be quite compact, so reducing expansion makes sense force_text=(0.75, 0), force_objects=(1, 0)) #With default forces it takes a very long time to converge, but higher values still produce very nice output ``` -------------------------------- ### Repelling Text Labels from a Plot Line using Interpolation Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb Demonstrates a technique to repel text labels from a plot line by generating virtual points along the line using interpolation. This prevents labels from overlapping the data. ```python from scipy import interpolate texts = plot_eucs_covers() f = interpolate.interp1d(eucs, covers) x = np.linspace(min(eucs), max(eucs), 500) y = f(x) adjust_text(texts, x, y, arrowprops=dict(arrowstyle="->", color='r', lw=0.5)) ``` -------------------------------- ### Fine-tuning AdjustText Force Parameters Source: https://context7.com/phlya/adjusttext/llms.txt This example demonstrates customizing the repulsion and attraction forces within adjust_text to control label layout behavior. It uses `force_text`, `force_pull`, and `force_static` to influence how labels move away from each other and towards their original positions. Requires matplotlib and adjustText. ```python import matplotlib.pyplot as plt from adjustText import adjust_text import numpy as np fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6)) # Same data for both plots np.random.seed(202) x = np.random.rand(18) * 8 y = np.random.rand(18) * 8 # Plot 1: Demonstrating force_text and force_pull ax1.scatter(x, y, s=50, c='orange', alpha=0.7) texts1 = [] for i, (xi, yi) in enumerate(zip(x, y)): texts1.append(ax1.text(xi, yi, f'T{i}', fontsize=9)) adjust_text( texts1, x=x, y=y, ax=ax1, arrowprops=dict(arrowstyle='-', color='black', lw=0.3), force_text=(0.5, 0.8), # Stronger repulsion between texts force_pull=(0.01, 0.01), # Weak pull towards original points expand=(1.1, 1.1), time_lim=2.0 ) ax1.set_title('Fine-tuned Forces: Strong Text Repulsion') # Plot 2: Demonstrating force_static (repulsion from static objects - not explicitly shown in this snippet but parameter is present) ax2.scatter(x, y, s=50, c='green', alpha=0.7) texts2 = [] for i, (xi, yi) in enumerate(zip(x, y)): texts2.append(ax2.text(xi, yi, f'T{i}', fontsize=9)) adjust_text( texts2, x=x, y=y, ax=ax2, arrowprops=dict(arrowstyle='->', color='red', lw=0.5), force_text=(0.2, 0.2), # Moderate repulsion between texts force_static=(1.0, 1.0),# Stronger static repulsion (if objects were present) force_pull=(0.05, 0.05), # Moderate pull towards original points expand=(1.2, 1.2), time_lim=2.0 ) ax2.set_title('Fine-tuned Forces: Moderate Static Repulsion') plt.tight_layout() plt.savefig('fine_tuned_forces.png', dpi=150, bbox_inches='tight') plt.show() ``` -------------------------------- ### Basic Text Adjustment on Scatter Plot Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Demonstrates the fundamental usage of adjust_text by plotting points and then adjusting the positions of their corresponding text labels to prevent overlap. The function takes a list of Matplotlib text objects and optionally the original x and y coordinates of the points. ```python np.random.seed(0) x, y = np.random.random((2,30)) fig, ax = plt.subplots() plt.plot(x, y, 'bo') texts = [plt.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))] np.random.seed(0) x, y = np.random.random((2,30)) fig, ax = plt.subplots() plt.plot(x, y, 'bo') texts = [ax.text(x[i], y[i], 'Text%s' %i, ha='center', va='center') for i in range(len(x))] adjust_text(texts) ``` -------------------------------- ### Plotting MTCARS Data with adjustText Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This Python code snippet visualizes the 'mtcars' dataset, plotting car weights against miles per gallon, and uses adjustText to resolve overlapping car name labels. It reads data from 'mtcars.csv' and applies text adjustment with specified parameters. Dependencies include pandas, numpy, and matplotlib. ```python mtcars = pd.read_csv('mtcars.csv') def plot_mtcars(adjust=False, *args, **kwargs): plt.figure(figsize=(9, 6)) plt.scatter(mtcars['wt'], mtcars['mpg'], s=15, c='r', edgecolors=(1,1,1,0)) texts = [] for x, y, s in zip(mtcars['wt'], mtcars['mpg'], mtcars['Car']): texts.append(plt.text(x, y, s, size=7)) if adjust: plt.title('%s iterations' % adjust_text(texts, precision=0.01, arrowprops=dict(arrowstyle="-", color='k', lw=0.5), save_steps=True, save_prefix='/home/s1529682/Projects/adjustText/examples/mtcars', **kwargs)) _ = plot_mtcars() ``` ```python plot_mtcars(adjust=True) ``` -------------------------------- ### Repelling Text from a Line Plot Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Demonstrates how to prevent text labels from overlapping a line in a plot by using the `x` and `y` arguments of `adjust_text`. These arguments define virtual points that the labels will try to avoid, effectively repelling them from the specified line. ```python from scipy import interpolate def plot_eucs_covers(): together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)] together.sort() text = [x for (x,y,z) in together] eucs = [y for (x,y,z) in together] covers = [z for (x,y,z) in together] plt.plot(eucs,covers,color="black", alpha=0.5) texts = [] for xt, yt, s in zip(eucs, covers, text): texts.append(plt.text(xt, yt, s, ha='center', va='center')) return texts, eucs, covers texts, eucs, covers = plot_eucs_covers() adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r', lw=0.5)) f = interpolate.interp1d(eucs, covers) x = np.linspace(min(eucs), max(eucs), 300) y = f(x) adjust_text(texts, x=x, y=y, arrowprops=dict(arrowstyle="->", color='r', lw=0.5)) ``` -------------------------------- ### Time Series Plot with adjustText Source: https://github.com/phlya/adjusttext/blob/master/figures/Examples.ipynb This Python code snippet demonstrates plotting time series data (page impressions over days) and using adjustText to manage overlapping date labels. It reads data from 'page-impressions.csv', formats dates, plots the data, and then adjusts the text labels. Dependencies include matplotlib, numpy, and locale. ```python import matplotlib.dates as mdates import locale locale.setlocale(locale.LC_ALL,'en_GB.utf8') #I have it set to Russian, without this dates don't work ``` ```python days, impressions = np.loadtxt("page-impressions.csv", unpack=True, converters={ 0: mdates.bytespdate2num('%Y-%m-%d')}) ``` ```python def plot_dates(adjust=False): plt.figure(figsize=(10, 7)) plt.plot_date(x=days, y=impressions) texts = [] for x, y in zip(days, impressions): texts.append(plt.text(x, y, int(y))) if adjust: plt.title(str(adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r', lw=0.5)))+' iterations') plot_dates(adjust=False) ``` ```python plot_dates(adjust=True) ``` -------------------------------- ### Plot MTCars Data with Matplotlib and Adjust Text Source: https://github.com/phlya/adjusttext/blob/master/docs/source/Examples.ipynb Creates a scatter plot of car weights versus miles per gallon using the MTCars dataset. This function demonstrates plotting individual car names and includes an option to adjust overlapping text labels for better readability. The plot uses Matplotlib for visualization. ```python import matplotlib.pyplot as plt import pandas as pd from adjustText import adjust_text mtcars = pd.read_csv('../../figures/mtcars.csv') def plot_mtcars(adjust=False, *args, **kwargs): plt.figure(figsize=(9, 6)) plt.scatter(mtcars['wt'], mtcars['mpg'], s=15, c='r', edgecolors=(1,1,1,0)) texts = [] for x, y, s in zip(mtcars['wt'], mtcars['mpg'], mtcars['Car']): texts.append(plt.text(x, y, s, size=9, ha='center', va='center')) plt.xlabel('wt') plt.ylabel('mpg') if adjust: adjust_text(texts, arrowprops=dict(arrowstyle="-", color='k', lw=0.5)) plot_mtcars(); plot_mtcars(adjust=True); ```