Related
I have some data that is broken down by day. For each day, I have a datapoint at the start and end of the day, each with a value between 0 and 100. I need to display this data as a grouped bar plot with the days on the x axis, values on the y axis and the bars colors are determined by their values. For each day, the left bar needs to have the corresponding start value, and the right bar displays the day's end value. The legend however needs to display information on the color rather than the trace
The plot basically needs to look like this but the legend needs to display "green", "amber", "red" instead of "start", "end".
I need the plot to look like this but with a legend describing the colors rather than the traces
Here is some code to reproduce the plot:
x = ["day"+str(i) for i in range(1,8)]
starts = [10, 50, 70, 75, 20, 50, 90]
ends = [95, 5, 80, 20, 50, 10, 75]
starts_colors = ['green', 'orange', 'red', 'red', 'green', 'orange', 'red']
ends_colors = ['red', 'green', 'red', 'green', 'orange', 'green', 'red']
And here is the code I have for the plot above.
layout = go.Layout(showlegend=True)
fig = go.Figure(layout=layout)
fig.add_trace(go.Bar(x=x, y=starts, name = 'start', marker=dict(color=starts_colors)))
fig.add_trace(go.Bar(x=x, y=ends, name = 'end', marker=dict(color=ends_colors)))
fig.show()
If I rearrange the data into 3 traces (one for each color) with the corresponding values in starts and ends, I end up with gaps between the bars. For example "day1" would have a gap in the middle because there is no orange bar for "day1".
This seems like a simple problem but I'm at a loss as to how to get it to work the way I'm supposed to.
this creates exactly the graph you requested
start by putting your sample data into a dataframe to open up Plotly Express
start by updating traces to use colors columns
adding legend is done. Really is not a functional legend as it cannot be used for filtering the figure, will just show unique colors used in figure. This is achieved by adding additional small traces
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"day": ["day" + str(i) for i in range(1, 8)],
"starts": [10, 50, 70, 75, 20, 50, 90],
"ends": [95, 5, 80, 20, 50, 10, 75],
"starts_colors": ["green", "orange", "red", "red", "green", "orange", "red"],
"ends_colors": ["red", "green", "red", "green", "orange", "green", "red"],
}
)
# build figure, hover_data / customdata is used to hold colors
fig = px.bar(
df,
x="day",
y=["starts", "ends"],
barmode="group",
hover_data={"starts_colors":False, "ends_colors":False},
)
# update colors of bars
fig.plotly_update(
data=[
t.update(marker_color=[c[i] for c in t.customdata])
for i, t in enumerate(fig.data)
]
)
# just for display purpose, create traces so that legend contains colors. does not connect with
# bars
fig.update_traces(showlegend=False).add_traces(
[
go.Bar(name=c, x=[fig.data[0].x[0]], marker_color=c, showlegend=True)
for c in np.unique(df.loc[:,["starts_colors","ends_colors"]].values.ravel())
]
)
in the Python package xlsxwriter, is it possible to format a part of a scatter chart series differently than another part? for example, a scatter chart where some sections of the line of a specific series are blue, and other sections of the same line are red. it is certainly possible in Excel itself by modifying specific data points.
I tried using the 'points' option in many combinations without success. I don't know which options are valid for it in a scatter chart.
UPDATE:
here is an example of what I'm trying to achieve. This was created directly in Excel, not through xlsxwriter. Notice how one section of the line is dashed and red, and another is a different thickness. To create it, simply select a data point and use the options in the sidebar to adjust formatting.
I've made an example that I think answers your question.
I'm using Python 3.5 and xlsxwriter 0.9.6.
In chart 1, I changed the color of the markers based on whether they were in a particular group. It's fairly straightforward if chart 1 is what you're looking for.
In chart 2, I show how to hard code a continuous line with different colors (there may be a better way to do this).
import xlsxwriter
import numpy as np
import pandas as pd
dates = pd.DataFrame({'excel_date':pd.date_range('1/1/2016', periods=12, freq='M')})
dates.excel_date = dates.excel_date - pd.datetime(1899, 12, 31)
data = np.array([11,20,25,35,40,48,44,31,25,38,49,60])
selection = np.array([4,5,6,8,11])
#Creating a list - you could hard code these lines if you prefer depending on the size of your series
diff_color_list = list()
for n in range(1, 13):
if n in selection:
diff_color_list.append({'fill':{'color': 'blue', 'width': 3.25}},)
else:
diff_color_list.append({'fill':{'color': 'red', 'width': 3.25}},)
#Workbook Creation
workbook = xlsxwriter.Workbook("test.xlsx")
format = workbook.add_format({'num_format':'mmm-yy'})
worksheet1 = workbook.add_worksheet("testsheet")
worksheet1.write('A1', 'Date')
worksheet1.write('B1', 'Data')
worksheet1.write_column('A2', dates.excel_date, format)
worksheet1.write_column('B2', data)
chart1 = workbook.add_chart({'type': 'scatter'})
# Configure the series.
chart1.add_series({'categories': '=testsheet!$A$2:$A$13',
'values': '=testsheet!$B$2:$B$13',
'points': diff_color_list
})
chart1.set_title ({'name': 'Results'})
chart1.set_x_axis({'name': 'Date'})
chart1.set_y_axis({'name': 'Data'})
chart1.set_legend({'none': True})
# Second chart with alternating line colors
chart2 = workbook.add_chart({'type': 'scatter',
'subtype': 'straight'})
chart2.add_series({'categories': '=testsheet!$A$2:$A$3',
'values': '=testsheet!$B$2:$B$3',
'line':{'color': 'blue'}
})
chart2.add_series({'categories': '=testsheet!$A$3:$A$4',
'values': '=testsheet!$B$3:$B$4',
'line':{'color': 'red'}
})
chart2.add_series({'categories': '=testsheet!$A$4:$A$5',
'values': '=testsheet!$B$4:$B$5',
'line':{'color': 'blue'}
})
chart2.set_title ({'name': 'Results'})
chart2.set_x_axis({'name': 'Date'})
chart2.set_y_axis({'name': 'Data'})
chart2.set_legend({'none': True})
worksheet1.insert_chart('D6', chart1)
worksheet1.insert_chart('L6', chart2)
workbook.close()
The question is a little bit confusing since you talk about changing the color of parts of a line but also about points.
I'm going to assume you are referring to changing the color of points/markers since as far as I know changing the color of line segments in a series isn't possible in Excel.
Anyway, it it possible to change marker colors in a scatter chart using XlsxWriter. For example:
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
# Add the worksheet data that the charts will refer to.
worksheet.write_column('A1', [1, 2, 3, 4, 5, 6])
worksheet.write_column('B1', [15, 40, 50, 20, 10, 50])
# Create a new scatter chart.
chart = workbook.add_chart({'type': 'scatter',
'subtype': 'straight_with_markers'})
# Configure the chart series. Increase the default marker size for clarity
# and configure the series points to
chart.add_series({
'categories': '=Sheet1!$A$1:$A$6',
'values': '=Sheet1!$B$1:$B$6',
'marker': {'type': 'square',
'size': 12},
'points': [
None,
None,
{'fill': {'color': 'green'},
'border': {'color': 'black'}},
None,
{'fill': {'color': 'red'},
'border': {'color': 'black'}},
],
})
# Turn off the legend for clarity.
chart.set_legend({'none': True})
# Insert the chart into the worksheet.
worksheet.insert_chart('D2', chart)
workbook.close()
Output:
i need to decrease the size of 3D pie Graph .i have changed $Radius=100 into $Radius=50 in pChart.class but not happening the size of graph .i am following the link
http://pchart.sourceforge.net/documentation.php?topic=exemple11
This should do:
// Pie chart with radius of 100
$picture->drawPieGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 150, 150, 100, PIE_PERCENTAGE);
// Pie chart with radius of 50
$picture->drawPieGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 150, 150, 50, PIE_PERCENTAGE);
I have a slider:
time_ax = fig.add_axes([0.1, 0.05, 0.8, 0.03])
var_time = Slider(time_ax, 'Time', 0, 100, valinit=10, valfmt='%0.0f')
var_time.on_changed(update)
and I want to customize the appearance of this slider:
I can add axisbg parameter to add_axes function, which will change default white background to assigned color, but that's all I see possible for now.
So, how to change other slider components:
silder border (default: black)
default value indicator (default: red)
slider progress (default: blue)
The slider border is just the spines of the Axes instance. The progress bar can be directly accessed for basic customization in the constructor, and the initial status indicator is an attribute of the slider. I was able to change all of those things:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig = plt.figure()
time_ax = fig.add_axes([0.1, 0.05, 0.8, 0.03])
# Facecolor and edgecolor control the slider itself
var_time = Slider(time_ax, 'Time', 0, 100, valinit=10, valfmt='%0.0f',
facecolor='c', edgecolor='r')
# The vline attribute controls the initial value line
var_time.vline.set_color('blue')
# The spines of the axis control the borders
time_ax.spines['left'].set_color('magenta')
time_ax.spines['right'].set_color('magenta')
time_ax.spines['bottom'].set_color('magenta')
time_ax.spines['top'].set_color('magenta')
The color of the box you can change when you define the axis of the "ax" box:
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0*np.sin(2*np.pi*f0*t)
l, = plt.plot(t,s, lw=2, color='red')
plt.axis([0, 1, -10, 10])
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.03, 0.25, 0.03, 0.65], axisbg=axcolor)
axamp = plt.axes([0.08, 0.25, 0.03, 0.65], axisbg=axcolor)
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
# The vline attribute controls the initial value line
samp.vline.set_color('green')
I use the fantastic Seaborn library for some summary stats in IPython Notebook. I recently switched over to a dark color theme for my notebooks and am trying to figure out the best seeings for Seaborn with a dark background. I am using the darkgrid style but the legends are still being printed in black which makes them impossible to read. Here is an example:
What is the best way to fix my styles of use of Seaborn to make the legends appear on white?
UPDATE:
I just noticed that the same problem exists with my Matplotlib graphs.. so my question is more general. What styles do you use to allow for white on dark plots so the legends are readable?
You can customize the seaborn style, and it tries to make it relatively easy to do so.
If you want to see each of the parameters that is considered part of the "style" definition, just call sns.axes_style() with no arguments, and it will return the current settings. As of 0.3.1 and for the default style ("darkgrid"), that looks like this:
{'axes.axisbelow': True,
'axes.edgecolor': 'white',
'axes.facecolor': '#EAEAF2',
'axes.grid': True,
'axes.labelcolor': '.15',
'axes.linewidth': 0,
'font.family': 'Arial',
'grid.color': 'white',
'grid.linestyle': '-',
'image.cmap': 'Greys',
'legend.frameon': False,
'legend.numpoints': 1,
'legend.scatterpoints': 1,
'lines.solid_capstyle': 'round',
'pdf.fonttype': 42,
'text.color': '.15',
'xtick.color': '.15',
'xtick.direction': 'out',
'xtick.major.size': 0,
'xtick.minor.size': 0,
'ytick.color': '.15',
'ytick.direction': 'out',
'ytick.major.size': 0,
'ytick.minor.size': 0}
A good heuristic is that you probably only need the parameters with "color" in the name, so you can filter it:
{k: v for k, v in sns.axes_style().items() if "color" in k}
returns
{'axes.edgecolor': 'white',
'axes.facecolor': '#EAEAF2',
'axes.labelcolor': '.15',
'grid.color': 'white',
'text.color': '.15',
'xtick.color': '.15',
'ytick.color': '.15'}
You can then pass a custom dictionary with values for these parameters into sns.set_style():
custom_style = {'axes.labelcolor': 'white',
'xtick.color': 'white',
'ytick.color': 'white'}
sns.set_style("darkgrid", rc=custom_style)
Why not simply
plt.style.use("dark_background")
sns.set_style("darkgrid")
Will make the background white so that you can see the text.
I find that adding this
plt.figure(facecolor='w')
each time I plot takes care of the axes background.