Matplotlib create text with colors corresponding to series












2















I am trying to create a plot with different colors for different series. The question arose when I tried to add the data in the figure as a text box.



The code I used is as follows:



import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import scipy.stats as stats

df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500], 'y':[3000, 2100, 1500, 3000, 2500, 2000], 'z':['a', 'b', 'c', 'd', 'e', 'f']})

fig, ax = plt.subplots(figsize=(8,6))

text_list =
color_list =

for i, row in df.iterrows():
mu, sigma, group = row['x'], row['y'], row['z']
x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
color = ax.get_lines()[-1].get_c()

ax = plt.gca()
ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color) #only retrieve RGB so blank text is not too light

text = r'{0}: {1} $pm$ {2}'.format(group, mu, sigma)
text_list.append(text)
color_list.append(color)

plt.gcf().text(0.68, 0.6, 'n'.join(text_list), bbox=dict(facecolor='white', edgecolor='black', pad=10.0, alpha=1), fontsize=14)
fig.show()


Which produces the following graph:
enter image description here



The texts within the bbox are all black. Ideally, each line in the text box should have a color identical to the corresponding series in the plot.



I was able to save two lists of texts and colors in the text_box_content and color_list. I also tried to add plt.gcf().text() within the for loop with dynamically-updated text locations, but the bounding boxes are created for each row instead of an overall-bounding box for all text.



It would be nicer if there is something conceptually similar to



plt.gcf().text(zip(text_list, color_list)) so each line can have its own color?










share|improve this question



























    2















    I am trying to create a plot with different colors for different series. The question arose when I tried to add the data in the figure as a text box.



    The code I used is as follows:



    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    import scipy.stats as stats

    df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500], 'y':[3000, 2100, 1500, 3000, 2500, 2000], 'z':['a', 'b', 'c', 'd', 'e', 'f']})

    fig, ax = plt.subplots(figsize=(8,6))

    text_list =
    color_list =

    for i, row in df.iterrows():
    mu, sigma, group = row['x'], row['y'], row['z']
    x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

    sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
    color = ax.get_lines()[-1].get_c()

    ax = plt.gca()
    ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color) #only retrieve RGB so blank text is not too light

    text = r'{0}: {1} $pm$ {2}'.format(group, mu, sigma)
    text_list.append(text)
    color_list.append(color)

    plt.gcf().text(0.68, 0.6, 'n'.join(text_list), bbox=dict(facecolor='white', edgecolor='black', pad=10.0, alpha=1), fontsize=14)
    fig.show()


    Which produces the following graph:
    enter image description here



    The texts within the bbox are all black. Ideally, each line in the text box should have a color identical to the corresponding series in the plot.



    I was able to save two lists of texts and colors in the text_box_content and color_list. I also tried to add plt.gcf().text() within the for loop with dynamically-updated text locations, but the bounding boxes are created for each row instead of an overall-bounding box for all text.



    It would be nicer if there is something conceptually similar to



    plt.gcf().text(zip(text_list, color_list)) so each line can have its own color?










    share|improve this question

























      2












      2








      2








      I am trying to create a plot with different colors for different series. The question arose when I tried to add the data in the figure as a text box.



      The code I used is as follows:



      import pandas as pd
      import matplotlib.pyplot as plt
      import seaborn as sns
      import numpy as np
      import scipy.stats as stats

      df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500], 'y':[3000, 2100, 1500, 3000, 2500, 2000], 'z':['a', 'b', 'c', 'd', 'e', 'f']})

      fig, ax = plt.subplots(figsize=(8,6))

      text_list =
      color_list =

      for i, row in df.iterrows():
      mu, sigma, group = row['x'], row['y'], row['z']
      x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

      sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
      color = ax.get_lines()[-1].get_c()

      ax = plt.gca()
      ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color) #only retrieve RGB so blank text is not too light

      text = r'{0}: {1} $pm$ {2}'.format(group, mu, sigma)
      text_list.append(text)
      color_list.append(color)

      plt.gcf().text(0.68, 0.6, 'n'.join(text_list), bbox=dict(facecolor='white', edgecolor='black', pad=10.0, alpha=1), fontsize=14)
      fig.show()


      Which produces the following graph:
      enter image description here



      The texts within the bbox are all black. Ideally, each line in the text box should have a color identical to the corresponding series in the plot.



      I was able to save two lists of texts and colors in the text_box_content and color_list. I also tried to add plt.gcf().text() within the for loop with dynamically-updated text locations, but the bounding boxes are created for each row instead of an overall-bounding box for all text.



      It would be nicer if there is something conceptually similar to



      plt.gcf().text(zip(text_list, color_list)) so each line can have its own color?










      share|improve this question














      I am trying to create a plot with different colors for different series. The question arose when I tried to add the data in the figure as a text box.



      The code I used is as follows:



      import pandas as pd
      import matplotlib.pyplot as plt
      import seaborn as sns
      import numpy as np
      import scipy.stats as stats

      df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500], 'y':[3000, 2100, 1500, 3000, 2500, 2000], 'z':['a', 'b', 'c', 'd', 'e', 'f']})

      fig, ax = plt.subplots(figsize=(8,6))

      text_list =
      color_list =

      for i, row in df.iterrows():
      mu, sigma, group = row['x'], row['y'], row['z']
      x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

      sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
      color = ax.get_lines()[-1].get_c()

      ax = plt.gca()
      ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color) #only retrieve RGB so blank text is not too light

      text = r'{0}: {1} $pm$ {2}'.format(group, mu, sigma)
      text_list.append(text)
      color_list.append(color)

      plt.gcf().text(0.68, 0.6, 'n'.join(text_list), bbox=dict(facecolor='white', edgecolor='black', pad=10.0, alpha=1), fontsize=14)
      fig.show()


      Which produces the following graph:
      enter image description here



      The texts within the bbox are all black. Ideally, each line in the text box should have a color identical to the corresponding series in the plot.



      I was able to save two lists of texts and colors in the text_box_content and color_list. I also tried to add plt.gcf().text() within the for loop with dynamically-updated text locations, but the bounding boxes are created for each row instead of an overall-bounding box for all text.



      It would be nicer if there is something conceptually similar to



      plt.gcf().text(zip(text_list, color_list)) so each line can have its own color?







      python matplotlib visualization seaborn






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 17:16









      Xiaoyu LuXiaoyu Lu

      452414




      452414
























          1 Answer
          1






          active

          oldest

          votes


















          3














          You could create a legend and colorize each legend item by the color of the line it belongs to. If you don't want to show the line itself in the legend, you could instead show the corresponding letter as a legend handle.



          import pandas as pd
          import matplotlib.pyplot as plt
          from matplotlib.legend_handler import HandlerBase
          from matplotlib.text import Text
          import seaborn as sns
          import numpy as np
          import scipy.stats as stats

          class TextHandler(HandlerBase):
          def create_artists(self, legend,tup ,xdescent, ydescent,
          width, height, fontsize,trans):
          tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
          ha="center", va="center", color=tup[1], fontweight="bold")
          return [tx]

          df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
          'y':[3000, 2100, 1500, 3000, 2500, 2000],
          'z':['a', 'b', 'c', 'd', 'e', 'f']})

          fig, ax = plt.subplots(figsize=(8,6))

          handles =
          labels =

          for i, row in df.iterrows():
          mu, sigma, group = row['x'], row['y'], row['z']
          x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

          sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
          color = ax.get_lines()[-1].get_c()

          ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)

          handles.append(("{}:".format(group), color))
          labels.append("{} $pm$ {}".format(mu, sigma))

          leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
          facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
          fontsize=10, handlelength=0.5)

          for h, t in zip(leg.legendHandles, leg.get_texts()):
          t.set_color(h.get_color())

          plt.show()


          enter image description here



          This is inspired by and makes partial use of the code from my answer to this question, which also holds an alternative in case you do not want to use a legend.






          share|improve this answer
























          • This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

            – Xiaoyu Lu
            Nov 14 '18 at 20:22











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305557%2fmatplotlib-create-text-with-colors-corresponding-to-series%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          You could create a legend and colorize each legend item by the color of the line it belongs to. If you don't want to show the line itself in the legend, you could instead show the corresponding letter as a legend handle.



          import pandas as pd
          import matplotlib.pyplot as plt
          from matplotlib.legend_handler import HandlerBase
          from matplotlib.text import Text
          import seaborn as sns
          import numpy as np
          import scipy.stats as stats

          class TextHandler(HandlerBase):
          def create_artists(self, legend,tup ,xdescent, ydescent,
          width, height, fontsize,trans):
          tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
          ha="center", va="center", color=tup[1], fontweight="bold")
          return [tx]

          df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
          'y':[3000, 2100, 1500, 3000, 2500, 2000],
          'z':['a', 'b', 'c', 'd', 'e', 'f']})

          fig, ax = plt.subplots(figsize=(8,6))

          handles =
          labels =

          for i, row in df.iterrows():
          mu, sigma, group = row['x'], row['y'], row['z']
          x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

          sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
          color = ax.get_lines()[-1].get_c()

          ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)

          handles.append(("{}:".format(group), color))
          labels.append("{} $pm$ {}".format(mu, sigma))

          leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
          facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
          fontsize=10, handlelength=0.5)

          for h, t in zip(leg.legendHandles, leg.get_texts()):
          t.set_color(h.get_color())

          plt.show()


          enter image description here



          This is inspired by and makes partial use of the code from my answer to this question, which also holds an alternative in case you do not want to use a legend.






          share|improve this answer
























          • This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

            – Xiaoyu Lu
            Nov 14 '18 at 20:22
















          3














          You could create a legend and colorize each legend item by the color of the line it belongs to. If you don't want to show the line itself in the legend, you could instead show the corresponding letter as a legend handle.



          import pandas as pd
          import matplotlib.pyplot as plt
          from matplotlib.legend_handler import HandlerBase
          from matplotlib.text import Text
          import seaborn as sns
          import numpy as np
          import scipy.stats as stats

          class TextHandler(HandlerBase):
          def create_artists(self, legend,tup ,xdescent, ydescent,
          width, height, fontsize,trans):
          tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
          ha="center", va="center", color=tup[1], fontweight="bold")
          return [tx]

          df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
          'y':[3000, 2100, 1500, 3000, 2500, 2000],
          'z':['a', 'b', 'c', 'd', 'e', 'f']})

          fig, ax = plt.subplots(figsize=(8,6))

          handles =
          labels =

          for i, row in df.iterrows():
          mu, sigma, group = row['x'], row['y'], row['z']
          x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

          sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
          color = ax.get_lines()[-1].get_c()

          ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)

          handles.append(("{}:".format(group), color))
          labels.append("{} $pm$ {}".format(mu, sigma))

          leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
          facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
          fontsize=10, handlelength=0.5)

          for h, t in zip(leg.legendHandles, leg.get_texts()):
          t.set_color(h.get_color())

          plt.show()


          enter image description here



          This is inspired by and makes partial use of the code from my answer to this question, which also holds an alternative in case you do not want to use a legend.






          share|improve this answer
























          • This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

            – Xiaoyu Lu
            Nov 14 '18 at 20:22














          3












          3








          3







          You could create a legend and colorize each legend item by the color of the line it belongs to. If you don't want to show the line itself in the legend, you could instead show the corresponding letter as a legend handle.



          import pandas as pd
          import matplotlib.pyplot as plt
          from matplotlib.legend_handler import HandlerBase
          from matplotlib.text import Text
          import seaborn as sns
          import numpy as np
          import scipy.stats as stats

          class TextHandler(HandlerBase):
          def create_artists(self, legend,tup ,xdescent, ydescent,
          width, height, fontsize,trans):
          tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
          ha="center", va="center", color=tup[1], fontweight="bold")
          return [tx]

          df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
          'y':[3000, 2100, 1500, 3000, 2500, 2000],
          'z':['a', 'b', 'c', 'd', 'e', 'f']})

          fig, ax = plt.subplots(figsize=(8,6))

          handles =
          labels =

          for i, row in df.iterrows():
          mu, sigma, group = row['x'], row['y'], row['z']
          x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

          sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
          color = ax.get_lines()[-1].get_c()

          ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)

          handles.append(("{}:".format(group), color))
          labels.append("{} $pm$ {}".format(mu, sigma))

          leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
          facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
          fontsize=10, handlelength=0.5)

          for h, t in zip(leg.legendHandles, leg.get_texts()):
          t.set_color(h.get_color())

          plt.show()


          enter image description here



          This is inspired by and makes partial use of the code from my answer to this question, which also holds an alternative in case you do not want to use a legend.






          share|improve this answer













          You could create a legend and colorize each legend item by the color of the line it belongs to. If you don't want to show the line itself in the legend, you could instead show the corresponding letter as a legend handle.



          import pandas as pd
          import matplotlib.pyplot as plt
          from matplotlib.legend_handler import HandlerBase
          from matplotlib.text import Text
          import seaborn as sns
          import numpy as np
          import scipy.stats as stats

          class TextHandler(HandlerBase):
          def create_artists(self, legend,tup ,xdescent, ydescent,
          width, height, fontsize,trans):
          tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
          ha="center", va="center", color=tup[1], fontweight="bold")
          return [tx]

          df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
          'y':[3000, 2100, 1500, 3000, 2500, 2000],
          'z':['a', 'b', 'c', 'd', 'e', 'f']})

          fig, ax = plt.subplots(figsize=(8,6))

          handles =
          labels =

          for i, row in df.iterrows():
          mu, sigma, group = row['x'], row['y'], row['z']
          x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)

          sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
          color = ax.get_lines()[-1].get_c()

          ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)

          handles.append(("{}:".format(group), color))
          labels.append("{} $pm$ {}".format(mu, sigma))

          leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
          facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
          fontsize=10, handlelength=0.5)

          for h, t in zip(leg.legendHandles, leg.get_texts()):
          t.set_color(h.get_color())

          plt.show()


          enter image description here



          This is inspired by and makes partial use of the code from my answer to this question, which also holds an alternative in case you do not want to use a legend.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 17:46









          ImportanceOfBeingErnestImportanceOfBeingErnest

          134k13148224




          134k13148224













          • This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

            – Xiaoyu Lu
            Nov 14 '18 at 20:22



















          • This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

            – Xiaoyu Lu
            Nov 14 '18 at 20:22

















          This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

          – Xiaoyu Lu
          Nov 14 '18 at 20:22





          This is an elegant and simple solution. And by putting everything in the legend I can also freely adjust the location of the box and everything else very easily. Thanks.

          – Xiaoyu Lu
          Nov 14 '18 at 20:22




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305557%2fmatplotlib-create-text-with-colors-corresponding-to-series%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues